第 3 章 - 探索對象、屬性和方法
我第一次介紹計算機是 Commodore 64,但我的第一部新式計算機是 286 12-Mhz IBM 複製品,記憶體為 1 MB、40 MB 硬碟,以及一部 5-1/4 英吋軟磁碟驅動器,以及執行 Microsoft DOS 3.3 的 CGA 監視器。
許多IT專業人員,就像我自己一樣,對命令行並不陌生,但當物件、屬性和方法的主題出現時,他們把鹿放在頭燈裡看說,「我不是開發人員」。猜猜什麼? 您不必是開發人員,就能使用PowerShell成功。 不要陷入術語。 並非所有專案最初都有意義,但在一點實際操作體驗之後,您將開始擁有這些“燈泡”時刻。 “Aha! 這就是這本書所談論的。
請務必嘗試計算機上的範例,以取得一些實際操作體驗。
需求
本章所示的一些範例需要 Active Directory PowerShell 模組。 此模組是適用於 Windows 的遠端伺服器 管理員 管理工具 (RSAT) 的一部分。 針對 1809 或更新版本的 Windows 組建,RSAT 工具會安裝為 Windows 功能。 Windows Home 上不支援 Active Directory。
- 如需安裝 RSAT 工具的相關信息,請參閱 Windows 管理模組。
- 如需舊版 Windows,請參閱 適用於 Windows 的 RSAT。
Get-Member
Get-Member
可協助您探索命令可用的物件、屬性和方法。
任何產生物件型輸出的命令都可以管線傳送至 Get-Member
。 屬性是專案的特性。 您的駕駛執照有一個名為眼睛色彩的屬性,而該屬性最常見的值為藍色和棕色。 方法是可在項目上採取的動作。 在保持駕駛執照範例中,其中一種方法是「撤銷」,因為機動車輛部門可以撤銷您的駕駛執照。
屬性
在下列範例中,我將擷取計算機上執行之 Windows Time 服務的相關信息。
Get-Service -Name w32time
Status Name DisplayName
------ ---- -----------
Running w32time Windows Time
Status、 Name 和 DisplayName 是屬性的範例,如先前的結果集所示。 Status 屬性的值是 Running
,Name 屬性的值是 w32time
,而 DisplayName 的值是 Windows Time
。
現在,我會將相同的命令傳送至 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();
上一個範例中結果的第一行包含一項非常重要的資訊。 TypeName 會告訴您傳回的物件類型。 在此範例中, 會傳回 System.ServiceProcess.ServiceController 物件。 這通常會在最後一個期間之後縮寫為 TypeName 的部分; 此範例中的 ServiceController。
一旦知道命令產生的物件類型之後,您可以使用這項資訊來尋找接受該物件類型的命令做為輸入。
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...
所有這些命令都有一個參數,可透過管線、參數輸入或兩者接受 ServiceController 物件類型。
請注意,屬性會比預設顯示的屬性多。 雖然預設不會顯示這些額外的屬性,但是可以從管線中選取這些屬性,方法是將命令管線管線傳送至 Select-Object
Cmdlet 並使用 Property 參數。 下列範例會藉由將 的結果Get-Service
傳送至 並Select-Object
指定*
通配符做為 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 :
您也可以使用 Property 參數值的逗號分隔清單來選取特定屬性。
Get-Service -Name w32time | Select-Object -Property Status, Name, DisplayName, ServiceType
Status Name DisplayName ServiceType
------ ---- ----------- -----------
Running w32time Windows Time Win32ShareProcess
根據預設,數據表中會傳回四個屬性,並在清單中傳回五個以上的屬性。 某些命令會使用自定義格式來覆寫資料表中預設顯示的屬性數目。
有數 Format-*
個 Cmdlet 可用來手動覆寫這些預設值。 最常見的是 Format-Table
和 Format-List
,這兩者都將在即將到來的章節中討論。
使用 指定屬性名稱 Select-Object
時,可以使用通配符。
Get-Service -Name w32time | Select-Object -Property Status, DisplayName, Can*
Status : Running
DisplayName : Windows Time
CanPauseAndContinue : False
CanShutdown : True
CanStop : True
在上一個範例中,Can*
用來做為 Property 參數的其中一個值,以傳回以 Can
開頭的所有屬性。 其中包括 CanPauseAndContinue、CanShutdown 和 CanStop。
方法
方法是可以採取的動作。 使用 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 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...
如您所見,有許多方法。 Stop 方法可用來停止 Windows 服務。
(Get-Service -Name w32time).Stop()
現在確認 Windows 時間服務確實已停止。
Get-Service -Name w32time
Status Name DisplayName
------ ---- -----------
Stopped w32time Windows Time
我很少發現自己使用方法,但他們是你需要注意的。 有時候您會遇到 Get-*
命令,而不需要對應的命令即可修改該專案。
通常,方法可以用來執行修改它的動作。 Get-SqlAgentJob
SqlServer PowerShell 模組中的 Cmdlet 是很好的範例。 模組會安裝為 SQL Server Management Studio (SMSS) 的一部分。 沒有對應的 Set-*
Cmdlet 存在,但方法可以用來完成相同的工作。
另一個瞭解方法的原因是許多初學者假設無法使用命令進行 Get-*
破壞性變更。 但是,如果不當使用,它們確實會導致嚴重的問題。
較佳的選項是使用 Cmdlet 在存在時執行動作。 請繼續啟動 Windows Time 服務,但這次會使用 Cmdlet 來啟動服務。
Get-Service -Name w32time | Start-Service -PassThru
Status Name DisplayName
------ ---- -----------
Running w32time Windows Time
根據預設, Start-Service
不會傳回任何結果,就像的 Get-Service
start 方法一樣。
但使用 Cmdlet 的其中一個優點是,Cmdlet 提供方法無法使用的其他功能。 在上述範例中, 使用了PassThru 參數。 這會導致通常不會產生輸出的 Cmdlet 產生輸出。
請小心有關 Cmdlet 輸出的假設。 我們都知道當你假設事情時會發生什麼。 我將擷取在 Windows 10 實驗室環境電腦上執行的 PowerShell 進程相關信息。
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
現在,我會使用同一個命令傳送給 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...
請注意,列出的屬性會比預設顯示更多。 檢視 的結果 Get-Member
時,所顯示的預設屬性數目不會顯示為屬性。 這是因為許多顯示的值,例如 NPM(K)
、 PM(K)
、 WS(K)
和 CPU(s)
,都是計算屬性。 若要判斷實際的屬性名稱,命令必須以管線傳送至 Get-Member
。
如果命令不會產生輸出,則無法透過管線傳送至 Get-Member
。 由於 Start-Service
預設不會產生任何輸出,因此當您嘗試將輸出傳送至 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
您可以使用 Cmdlet 指定 PassThru 參數Start-Service
,使其產生輸出,然後透過管線傳送至 Get-Member
,而不會發生錯誤。
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();
若要使用管線傳送至 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], InvalidOperationException
+ FullyQualifiedErrorId : NoObjectInGetMember,Microsoft.PowerShell.Commands.GetMemberCommand
Out-Host
直接寫入 PowerShell 主機,但不會產生管線的對象型輸出。 因此,它無法透過管線傳送至 Get-Member
。
Active Directory
注意
本章需求區段中所列的遠端伺服器 管理員 工具,必須完成本節。 此外,如這本書簡介中所述,您的 Windows 10 實驗室環境計算機必須是實驗室環境網域的成員。
搭配 Get-Command
Module 參數使用,以判斷安裝遠端伺服器管理工具時,哪些命令會新增為ActiveDirectory PowerShell 模組的一部分。
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...
...
ActiveDirectory PowerShell 模組共新增了 147 個命令。 這些命令的某些命令預設只會傳回部分可用的屬性。
您是否注意到此課程模組中命令的名稱有什麼不同? 命令的名詞部分具有AD前置詞。 在大部分模組的命令上,通常會看到這一點。 前置詞的設計是為了協助防止命名衝突。
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;}
即使您只模糊地熟悉 Active Directory,您可能也知道使用者帳戶的屬性比此範例中所示的還要多。
Cmdlet Get-ADUser
具有 Properties 參數,可用來指定您想要傳回的其他 (非預設) 屬性。 指定 *
通配符會傳回所有通配符。
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...
現在看起來更像了。
您可以考慮為什麼 Active Directory 使用者帳戶的屬性預設會受到如此限制的原因嗎? 想像一下,如果您在生產 Active Directory 環境中傳回每個用戶帳戶的每個屬性。 請考慮效能降低的原因,不僅對域控制器本身,而且對網路造成影響。 毫無疑問,無論如何,你實際上都需要每一個屬性。 當您嘗試判斷哪些屬性存在時,傳回單一用戶帳戶的所有屬性是完全可接受的。
在建立原型時,執行命令多次並不罕見。 如果您要執行一些龐大的查詢,請查詢一次,並將結果儲存在變數中。 然後使用變數的內容,而不是重複使用一些昂貴的查詢。
$Users = Get-ADUser -Identity mike -Properties *
使用變數的內容 $Users
,而不是多次執行先前的命令。
請記住,對 Active Directory 中的該用戶進行變更時,不會更新變數的內容。
您可以使用管線 $Users
將變數傳送至 Get-Member
以探索可用的屬性。
$Users | Get-Member
然後,將管線 $Users
傳送至 Select-Object
來選取個別屬性,而不需要多次查詢 Active Directory。
$Users | Select-Object -Property Name, LastLogonDate, LastBadPasswordAttempt
如果您要多次查詢 Active Directory,請使用 Properties 參數來指定您想要的任何非預設屬性。
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
摘要
在本章中,您已瞭解如何判斷命令產生的物件類型、如何判斷命令可用的屬性和方法,以及如何使用限制預設傳回之屬性的命令。
檢閱
- Cmdlet 會產生何種類型的物件
Get-Process
? - 如何判斷命令可用的屬性為何?
- 如果命令存在來取得某個專案,但無法設定相同的專案,您應該檢查什麼?
- 根據預設,不產生輸出的特定命令如何產生輸出?
- 如果您要處理會產生大量輸出的命令結果,您應該考慮怎麼做?
建議閱讀資料
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應