[玩转系统] 发现对象、属性和方法
作者:精品下载站 日期:2024-12-14 03:05:57 浏览:14 分类:玩电脑
发现对象、属性和方法
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 build 1809 或更高版本(包括 Windows 11),则可以将 RSAT 安装为 Windows 功能。
笔记
Windows 家庭版不支持 Active Directory。
- 有关安装 RSAT 的信息,请参阅 Windows 管理模块。
- 对于旧版本的 Windows,请参阅适用于 Windows 的 RSAT。
Get-Member
Get-Member
提供对与 PowerShell 命令关联的对象、属性和方法的深入了解。您可以将任何生成基于对象的输出的 PowerShell 命令通过管道传递给 Get-Member
。当您将命令的输出通过管道传递给 Get-Member
时,它会显示命令返回的对象的结构,详细说明其属性和方法。
- 属性:对象的属性。
- 方法:您可以对对象执行的操作。
为了说明这个概念,请以驾驶执照作为类比。与任何对象一样,驾驶执照也具有属性,例如眼睛颜色,通常包括蓝色
和棕色
值。相反,方法代表您可以对对象执行的操作。例如,吊销是机动车辆管理局可以对驾驶执照执行的一种方法。
特性
要使用 PowerShell 检索有关系统上的 Windows 时间服务的详细信息,请使用 Get-Service
cmdlet。
Get-Service -Name w32time
结果包括状态、名称和DisplayName属性。 状态属性指示服务正在运行
。 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-Service
传输到 Get-Member
时,显示的属性比默认显示的属性要多。尽管默认情况下不显示这些附加属性,但您可以通过管道传输到 Select-Object
并使用 Property 参数来选择它们。以下示例通过将 Get-Service
的结果通过管道传输到 Select-Object
并指定 *
通配符作为属性参数。
Get-Service -Name w32time | Select-Object -Property *
默认情况下,PowerShell 以表的形式返回四个属性,以列表的形式返回五个或更多属性。但是,某些命令应用自定义格式来覆盖表中显示的默认属性数量。您可以使用 Format-Table
和 Format-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-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...
您可以使用停止方法来停止Windows 服务。您必须从提升的 PowerShell 会话运行此命令。
(Get-Service -Name w32time).Stop()
查询 Windows 时间服务的状态以确认其已停止。
Get-Service -Name w32time
Status Name DisplayName
------ ---- -----------
Stopped w32time Windows Time
您可能会谨慎使用方法,但您应该了解它们。有时,您会发现 Get-*
命令没有相应的 Set-*
命令。通常,您可以找到在这种情况下执行 Set-*
操作的方法。 SqlServer PowerShell 模块中的 Get-SqlAgentJob
cmdlet 就是一个很好的示例。不存在相应的 Set-*
cmdlet,但您可以使用一种方法来完成相同的任务。有关 SqlServer PowerShell 模块和安装说明的详细信息,请参阅 SQL Server PowerShell 概述。
了解方法的另一个原因是,一些 PowerShell 用户认为您无法使用 Get-*
命令进行破坏性更改,但如果误用,它们实际上可能会导致严重问题。
更好的选择是使用专用 cmdlet(如果存在)来执行操作。例如,使用 Start-Service
cmdlet 启动 Windows 时间服务。
默认情况下,Start-Service
与 Get-Service
的 Start 方法一样,不会返回任何结果。但是,使用 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
是计算属性。您必须通过管道将命令发送给 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
要避免此错误,请使用 Start-Service
指定 PassThru 参数。如前所述,添加 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
活动目录
笔记
如先决条件一章中所述,请确保已安装本部分的 RSAT。此外,您的实验室环境计算机必须是实验室环境 Active Directory 域的成员。
要识别安装 RSAT 后添加到 ActiveDirectory PowerShell 模块的命令,请将 Get-Command
与 Module 参数结合使用。以下示例列出了 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 *
您可以通过将 $Users
变量通过管道传递给 Get-Member
来探索可用属性。
$Users | Get-Member -MemberType Properties
要查看特定属性,例如 Name、LastLogonDate 和 LastBadPasswordAttempt,请将 $Users
变量通过管道传递给 选择对象
。此方法根据 $Users
变量的内容显示所需的属性及其值,从而无需多次查询 Active Directory。与重复执行 Get-ADUser
命令相比,这是一种更节省资源的方法。
$Users | Select-Object -Property Name, LastLogonDate, LastBadPasswordAttempt
查询 Active Directory 时,使用 Get-ADUser
的 Properties 参数过滤源数据,仅返回必要的属性。
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
概括
在本章中,您学习了如何确定命令生成的对象类型、命令可用的属性和方法,以及如何使用限制默认返回的属性的命令。
审查
Get-Process
cmdlet 生成什么类型的对象?- 如何确定命令的可用属性是什么?
- 如果存在获取某些内容但不设置相同内容的命令,您应该检查什么?
- 如何使一些默认不返回输出的命令生成输出?
- 在对产生大量输出的命令进行原型设计时,您应该考虑做什么?
参考
- Get-Member
- 查看对象结构 (Get-Member)
- about_Objects
- about_属性
- about_方法
- 没有 PowerShell Cmdlet 来启动或停止某些操作?不要忘记检查 Get Cmdlet 上的方法
后续步骤
在下一章中,您将了解单行代码和管道。
猜你还喜欢
- 03-30 [玩转系统] 如何用批处理实现关机,注销,重启和锁定计算机
- 02-14 [系统故障] Win10下报错:该文件没有与之关联的应用来执行该操作
- 01-07 [系统问题] Win10--解决锁屏后会断网的问题
- 01-02 [系统技巧] Windows系统如何关闭防火墙保姆式教程,超详细
- 12-15 [玩转系统] 如何在 Windows 10 和 11 上允许多个 RDP 会话
- 12-15 [玩转系统] 查找 Exchange/Microsoft 365 中不活动(未使用)的通讯组列表
- 12-15 [玩转系统] 如何在 Windows 上安装远程服务器管理工具 (RSAT)
- 12-15 [玩转系统] 如何在 Windows 上重置组策略设置
- 12-15 [玩转系统] 如何获取计算机上的本地管理员列表?
- 12-15 [玩转系统] 在 Visual Studio Code 中连接到 MS SQL Server 数据库
- 12-15 [玩转系统] 如何降级 Windows Server 版本或许可证
- 12-15 [玩转系统] 如何允许非管理员用户在 Windows 中启动/停止服务
取消回复欢迎 你 发表评论:
- 精品推荐!
-
- 最新文章
- 热门文章
- 热评文章
[影视] 黑道中人 Alto Knights(2025)剧情 犯罪 历史 电影
[古装剧] [七侠五义][全75集][WEB-MP4/76G][国语无字][1080P][焦恩俊经典]
[实用软件] 虚拟手机号 电话 验证码 注册
[电视剧] 安眠书店/你 第五季 You Season 5 (2025) 【全10集】
[电视剧] 棋士(2025) 4K 1080P【全22集】悬疑 犯罪 王宝强 陈明昊
[软件合集] 25年6月5日 精选软件22个
[软件合集] 25年6月4日 精选软件36个
[短剧] 2025年06月04日 精选+付费短剧推荐33部
[短剧] 2025年06月03日 精选+付费短剧推荐25部
[软件合集] 25年6月3日 精选软件44个
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电视剧] 欢乐颂.5部全 (2016-2024)
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[影视] 【稀有资源】香港老片 艺坛照妖镜之96应召名册 (1996)
[剧集] 神经风云(2023)(完结).4K
[剧集] [BT] [TVB] [黑夜彩虹(2003)] [全21集] [粤语中字] [TV-RMVB]
[实用软件] 虚拟手机号 电话 验证码 注册
[资源] B站充电视频合集,包含多位重量级up主,全是大佬真金白银买来的~【99GB】
[影视] 内地绝版高清录像带 [mpg]
[书籍] 古今奇书禁书三教九流资料大合集 猎奇必备珍藏资源PDF版 1.14G
[电视剧] [突围] [45集全] [WEB-MP4/每集1.5GB] [国语/内嵌中文字幕] [4K-2160P] [无水印]
[剧集] [央视][笑傲江湖][2001][DVD-RMVB][高清][40集全]李亚鹏、许晴、苗乙乙
[电影] 美国队长4 4K原盘REMUX 杜比视界 内封简繁英双语字幕 49G
[电影] 死神来了(1-6)大合集!
[软件合集] 25年05月13日 精选软件16个
[精品软件] 25年05月15日 精选软件18个
[绝版资源] 南与北 第1-2季 合集 North and South (1985) /美国/豆瓣: 8.8[1080P][中文字幕]
[软件] 25年05月14日 精选软件57个
[短剧] 2025年05月14日 精选+付费短剧推荐39部
[短剧] 2025年05月15日 精选+付费短剧推荐36部
- 最新评论
-
- 热门tag