3. fejezet – Objektumok, tulajdonságok és metódusok felfedezése

A számítógépek első bemutatása egy Commodore 64 volt, de az első modern számítógépem egy 286 12 Mhz-es IBM-klón volt 1 megabájt memóriával, egy 40 megabájtos merevlemezzel és egy 5-1/4 hüvelykes hajlékonylemez-meghajtóval, a Microsoft DOS 3.3-at futtató CGA monitorral.

Sok informatikai szakember, mint én, nem idegen a parancssortól, de amikor az objektumok, tulajdonságok és módszerek tárgya megjelenik, a szarvas a fényszórókban megjelenik, és azt mondja: "Nem vagyok fejlesztő." Mit gondolsz? Nem kell fejlesztőnek lennie ahhoz, hogy sikeres legyen a PowerShell-lel. Ne ássa le a terminológiát. Kezdetben nem mindennek van értelme, de egy kis gyakorlati tapasztalat után elkezdheti azokat a "villanykörte" pillanatokat. "Aha! Szóval erről beszélt a könyv."

Mindenképpen próbálja ki a példákat a számítógépen, hogy megszerezzen néhányat a gyakorlati élményből.

Követelmények

Az Ebben a fejezetben bemutatott néhány példa az Active Directory PowerShell-modulra van szükség. A modul a Windows távoli kiszolgálói Rendszergazda istration Tools (RSAT) része. A Windows 1809(vagy újabb) buildje esetében az RSAT-eszközök Windows-funkcióként vannak telepítve. Az Active Directory támogatása windowsos kezdőlapon nem érhető el.

  • Az RSAT-eszközök telepítéséről további információt a Windows Management moduljaiban talál.
  • A Windows régebbi verzióit lásd: RSAT for Windows.

Get-Member

Get-Member segít felderíteni, hogy milyen objektumok, tulajdonságok és metódusok érhetők el a parancsokhoz. Az objektumalapú kimenetet előállító parancsok a következőre Get-Memberirányíthatók: . A tulajdonság egy elem jellemzője. Az illesztőprogram-licencben van egy szemszín nevű tulajdonság, és a tulajdonság leggyakoribb értékei a kék és a barna. A metódus egy elemen végrehajtható művelet. A jogosítvány-példában az egyik módszer a "Visszavonás", mivel a gépjárműosztály visszavonhatja a jogosítványát.

Tulajdonságok

Az alábbi példában a számítógépen futó Windows Time szolgáltatással kapcsolatos információkat fogom lekérni.

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

Az Állapot, a Név és a DisplayName az előző eredményhalmazban látható tulajdonságokra mutat példákat. Az Állapot tulajdonság értéke, a Név tulajdonság w32timeértéke, a DisplayName Windows Time értéke Runningpedig .

Most ugyanezt a parancsot a következőre fogom csövezni 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();

Az előző példában szereplő eredmények első sora egy nagyon fontos információt tartalmaz. A TypeName azt jelzi, hogy milyen típusú objektum lett visszaadva. Ebben a példában egy System.ServiceProcess.ServiceController objektum lett visszaadva. Ezt gyakran a TypeName részeként rövidítve, az utolsó időszak után; A ServiceController ebben a példában.

Ha már tudja, hogy a parancs milyen típusú objektumot hoz létre, ezen információk segítségével megkeresheti azokat a parancsokat, amelyek bemenetként elfogadják az adott objektumtípust.

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

Mindegyik parancs rendelkezik egy paraméterrel, amely folyamat, paraméterbemenet vagy mindkettő alapján elfogadja a ServiceController-objektumtípust .

Figyelje meg, hogy az alapértelmezés szerint megjelenítettnél több tulajdonság van. Bár ezek a további tulajdonságok alapértelmezés szerint nem jelennek meg, kiválaszthatók a folyamatból úgy, hogy a parancsot a Select-Object parancsmagba helyezik, és a Tulajdonság paramétert használják. Az alábbi példa az összes tulajdonságot kiválasztja úgy, hogy a Get-Service tulajdonság paraméter értékeként a * helyettesítő karaktert adja Select-Object meg.

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           :

Adott tulajdonságok a tulajdonságparaméter értékének vesszővel tagolt listájával is kijelölhetők.

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

Alapértelmezés szerint négy tulajdonságot ad vissza egy táblában, és öt vagy több tulajdonságot ad vissza egy listában. Egyes parancsok egyéni formázással felülbírálják, hogy egy tábla hány tulajdonsága jelenjen meg alapértelmezés szerint. Ezen alapértelmezett értékek manuális felülbírálásához több Format-* parancsmag is használható. A leggyakoribbak, Format-Table és Format-Listmindkettőt egy közelgő fejezetben ismertetjük.

A tulajdonságnevek Select-Objectmegadásakor helyettesítő karakterek használhatók.

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

Az előző példában Can* a Tulajdonság paraméter egyik értékeként használtuk az összes olyan tulajdonság visszaadásához, amely a következővel Cankezdődik: . Ezek közé tartozik a CanPauseAndContinue, a CanShutdown és a CanStop.

Metódusok

A metódusok végrehajtható műveletek. A MemberType paraméter használatával szűkítheti az eredményeketGet-Member, hogy csak a metódusok jelenjenek Get-Servicemeg.

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

Mint látható, számos módszer létezik. A Stop metódussal leállíthat egy Windows-szolgáltatást.

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

Most ellenőrizze, hogy a Windows időszolgáltatás valóban le lett-e állítva.

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

Ritkán találom magam módszereket használva, de ezek olyan dolog, amit tudnod kell. Vannak olyan esetek, amikor egy Get-* parancshoz nem tartozik megfelelő parancs az elem módosításához. Gyakran egy metódussal olyan műveletet hajthat végre, amely módosítja azt. Erre Get-SqlAgentJob jó példa az SqlServer PowerShell-modul parancsmagja. A modul az SQL Server Management Studio (SMSS) részeként telepíthető. Nincs megfelelő Set-* parancsmag, de egy metódussal elvégezheti ugyanazt a feladatot.

A módszerekkel való ismerkedés másik oka, hogy sok kezdő feltételezi, hogy a parancsokkal Get-* nem lehet romboló módosításokat végrehajtani. De valóban komoly problémákat okozhatnak, ha helytelenül használják.

Jobb megoldás, ha parancsmaggal hajtja végre a műveletet, ha van ilyen. Indítsa el a Windows Time szolgáltatást, kivéve, ha ezúttal a parancsmagot használja a szolgáltatások indításához.

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

Alapértelmezés szerint nem ad vissza eredményt ugyanúgy, Start-Service mint a kezdőmetódus Get-Service. A parancsmagok használatának egyik előnye azonban az, hogy a parancsmag sokszor kínál olyan további funkciókat, amelyek nem érhetők el egy metódussal. Az előző példában a PassThru paramétert használtuk. Ez egy olyan parancsmagot eredményez, amely általában nem hoz létre kimenetet.

Legyen óvatos a parancsmag kimenetével kapcsolatos feltételezésekkel. Mindannyian tudjuk, mi történik, ha feltételezzük a dolgokat. A Windows 10 tesztkörnyezeti számítógépen futó PowerShell-folyamatról fogok információt lekérni.

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

Most ugyanezt a parancsot fogom lekérni a Get-Member parancshoz:

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

Figyelje meg, hogy az alapértelmezettnél több tulajdonság van felsorolva. A megjelenített alapértelmezett tulajdonságok száma nem jelenik meg tulajdonságokként a találatok Get-Membermegtekintésekor. Ennek az az oka, hogy a megjelenített értékek közül sok , például NPM(K)PM(K), WS(K), és CPU(s)számított tulajdonság. A tényleges tulajdonságnevek meghatározásához a parancsot a következőre kell átirányítani Get-Member: .

Ha egy parancs nem hoz létre kimenetet, az nem hajtható végre Get-Member. Mivel Start-Service alapértelmezés szerint nem hoz létre kimenetet, hibaüzenetet generál, amikor megpróbálja becsúszni 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

A PassThru paraméter megadható a Start-Service parancsmaggal, hogy kimenetet hozzon létre, amely ezután hiba nélkül lesz átirányítva 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();

A parancsnak Get-Memberobjektumalapú kimenetet kell létrehoznia.

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 közvetlenül a PowerShell-gazdagépre ír, de nem hoz létre objektumalapú kimenetet a folyamathoz. Így nem lehet becsúszni.Get-Member

Active Directory

Feljegyzés

A szakasz befejezéséhez a távoli kiszolgáló Rendszergazda istration Tools (Távoli kiszolgáló Rendszergazda istration Tools) szükséges, amely a jelen fejezet követelmények szakaszában szerepel. Emellett, ahogy a könyv bevezetőjében is említettük, a Windows 10 tesztkörnyezeti számítógépnek a tesztkörnyezet tartományának tagjának kell lennie.

A Get-Command Modul paraméterrel meghatározhatja, hogy milyen parancsok lettek hozzáadva az ActiveDirectory PowerShell modul részeként a távoli kiszolgálófelügyeleti eszközök telepítésekor.

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

Összesen 147 parancs lett hozzáadva az ActiveDirectory PowerShell-modul részeként. Ezen parancsok egyes parancsai alapértelmezés szerint csak az elérhető tulajdonságok egy részét adják vissza.

Észlelt valami mást a modul parancsainak nevével kapcsolatban? A parancsok főnévi része AD-előtaggal rendelkezik. Ez általában a legtöbb modul parancsán látható. Az előtag úgy lett kialakítva, hogy megakadályozza az elnevezési ütközéseket.

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

Még ha csak homályosan is ismeri az Active Directoryt, valószínűleg tisztában van azzal, hogy egy felhasználói fiók több tulajdonsággal rendelkezik, mint ami a példában látható.

A Get-ADUser parancsmag egy Tulajdonságok paraméterrel rendelkezik, amely a visszaadni kívánt további (nem alapértelmezett) tulajdonságok megadására szolgál. * A helyettesítő karakter megadása mindet visszaadja.

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

Most, hogy úgy néz ki, mint ez.

Gondoljon arra, hogy egy Active Directory-felhasználói fiók tulajdonságai miért lennének ilyen korlátozottak alapértelmezés szerint? Tegyük fel, hogy az éles Active Directory-környezetben minden felhasználói fiók minden tulajdonságát visszaadta. Gondoljon arra a teljesítménycsökkenésre, amelyet nem csak maguk a tartományvezérlők, hanem a hálózata is okozhat. Nem biztos, hogy minden ingatlanra szüksége lesz. Az egyetlen felhasználói fiók összes tulajdonságának visszaadása tökéletesen elfogadható, ha meg szeretné állapítani, hogy mely tulajdonságok léteznek.

Nem ritka, hogy többször futtat egy parancsot, amikor prototípust készít. Ha hatalmas lekérdezést szeretne végrehajtani, kérdezd le egyszer, és tárold az eredményeket egy változóban. Ezután használja a változó tartalmát ahelyett, hogy ismétlődően használnál valamilyen drága lekérdezést.

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

Az előző parancs többszöri futtatása helyett használja a $Users változó tartalmát. Ne feledje, hogy a változó tartalma nem frissül, amikor módosítja a felhasználót az Active Directoryban.

A változót a $Users rendelkezésre álló tulajdonságok felderítéséhez Get-Member csövezheti.

$Users | Get-Member

Ezután válassza ki az egyes tulajdonságokat a piping $UsersSelect-Objectsegítségével, mindezt anélkül, hogy többször kellene lekérdeznie az Active Directoryt.

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

Ha többször szeretné lekérdezni az Active Directoryt, a Tulajdonságok paraméterrel adja meg a kívánt nem alapértelmezett tulajdonságokat.

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

Összegzés

Ebben a fejezetben megtanulta, hogyan határozhatja meg, hogy a parancs milyen típusú objektumot hoz létre, hogyan állapíthatja meg, hogy milyen tulajdonságok és metódusok érhetők el egy parancshoz, és hogyan dolgozhat olyan parancsokkal, amelyek korlátozzák az alapértelmezés szerint visszaadott tulajdonságokat.

Áttekintés

  1. Milyen típusú objektumot hoz létre a Get-Process parancsmag?
  2. Hogyan állapítható meg, hogy a parancsok milyen tulajdonságokat használhatnak?
  3. Ha van egy parancs, amely lekért valamit, de nem ugyanarra a beállításra, mit kell ellenőriznie?
  4. Hogyan lehet olyan parancsokat létrehozni, amelyek alapértelmezés szerint nem hoznak létre kimenetet?
  5. Ha egy olyan parancs eredményeivel dolgozik, amely hatalmas mennyiségű kimenetet hoz létre, mit érdemes megfontolnia?