Bab 3 - Menemukan objek, properti, dan metode
Pengantar pertama saya ke komputer adalah Commodore 64, tetapi komputer modern pertama saya adalah klon IBM 286 12-Mhz dengan memori 1 megabyte, hard drive 40 megabyte, dan satu drive disk floppy 5-1/4 inci dengan monitor CGA yang menjalankan Microsoft DOS 3.3.
Banyak Profesional IT, seperti saya sendiri, tidak asing dengan baris perintah, tetapi ketika subjek objek, properti, dan metode muncul, mereka mendapatkan kijang dalam tampilan lampu depan dan mengatakan, "Saya bukan pengembang." Coba tebak? Anda tidak perlu menjadi pengembang untuk sukses dengan PowerShell. Jangan terjebak dalam terminologi. Tidak semuanya mungkin masuk akal pada awalnya, tetapi setelah sedikit pengalaman langsung, Anda akan mulai memiliki momen "bola lampu" tersebut. "Aha! Jadi itulah yang dibicarakan buku itu."
Pastikan untuk mencoba contoh di komputer Anda untuk mendapatkan beberapa pengalaman langsung tersebut.
Persyaratan
Modul PowerShell Direktori Aktif diperlukan oleh beberapa contoh yang ditunjukkan dalam bab ini. Modul ini adalah bagian dari Remote Server Administration Tools (RSAT) untuk Windows. Untuk build Windows 1809 (atau lebih tinggi), alat RSAT diinstal sebagai fitur Windows. Dukungan untuk Direktori Aktif tidak tersedia di Windows Home.
- Untuk informasi tentang menginstal alat RSAT, lihat modul Manajemen Windows.
- Untuk versi Windows yang lebih lama, lihat RSAT untuk Windows.
Get-Member
Get-Member
membantu Anda menemukan objek, properti, dan metode apa yang tersedia untuk perintah.
Perintah apa pun yang menghasilkan output berbasis objek dapat disalurkan ke Get-Member
. Properti adalah karakteristik tentang item. SIM Anda memiliki properti yang disebut warna mata dan nilai paling umum untuk properti tersebut adalah biru dan coklat. Metode adalah tindakan yang dapat diambil pada item. Dalam tinggal dengan contoh SIM, salah satu metodenya adalah "Cabut" karena departemen kendaraan bermotor dapat mencabut SIM Anda.
Properti
Dalam contoh berikut, saya akan mengambil informasi tentang layanan Windows Time yang berjalan di komputer saya.
Get-Service -Name w32time
Status Name DisplayName
------ ---- -----------
Running w32time Windows Time
Status, Nama, dan DisplayName adalah contoh properti seperti yang ditunjukkan pada kumpulan hasil sebelumnya. Nilai untuk properti Status adalah Running
, nilai untuk properti Nama adalah w32time
, dan nilai untuk DisplayName adalah Windows Time
.
Sekarang saya akan menyalurkan perintah yang sama ke 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();
Baris pertama hasil dalam contoh sebelumnya berisi satu bagian dari informasi yang sangat penting. TypeName memberi tahu Anda tipe objek apa yang dikembalikan. Dalam contoh ini, objek System.ServiceProcess.ServiceController dikembalikan. Ini sering disingkat sebagai bagian dari TypeName tepat setelah periode terakhir; ServiceController dalam contoh ini.
Setelah Anda mengetahui jenis objek apa yang dihasilkan perintah, Anda dapat menggunakan informasi ini untuk menemukan perintah yang menerima jenis objek tersebut sebagai input.
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...
Semua perintah tersebut memiliki parameter yang menerima jenis objek ServiceController berdasarkan alur, input parameter, atau keduanya.
Perhatikan bahwa ada lebih banyak properti daripada yang ditampilkan secara default. Meskipun properti tambahan ini tidak ditampilkan secara default, properti tersebut dapat dipilih dari alur dengan mempipa perintah ke Select-Object
cmdlet dan menggunakan parameter Properti . Contoh berikut memilih semua properti dengan mempipa hasil ke Get-Service
Select-Object
dan menentukan *
karakter kartubebas sebagai nilai untuk parameter Properti .
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 :
Properti tertentu juga dapat dipilih menggunakan daftar yang dipisahkan koma untuk nilai parameter Properti .
Get-Service -Name w32time | Select-Object -Property Status, Name, DisplayName, ServiceType
Status Name DisplayName ServiceType
------ ---- ----------- -----------
Running w32time Windows Time Win32ShareProcess
Secara default, empat properti dikembalikan dalam tabel dan lima atau lebih dikembalikan dalam daftar. Beberapa perintah menggunakan pemformatan kustom untuk menimpa berapa banyak properti yang ditampilkan secara default dalam tabel.
Ada beberapa Format-*
cmdlet yang dapat digunakan untuk mengambil alih default ini secara manual. Yang paling umum adalah Format-Table
dan Format-List
, yang keduanya akan dibahas dalam bab yang akan datang.
Karakter kartubebas dapat digunakan saat menentukan nama properti dengan Select-Object
.
Get-Service -Name w32time | Select-Object -Property Status, DisplayName, Can*
Status : Running
DisplayName : Windows Time
CanPauseAndContinue : False
CanShutdown : True
CanStop : True
Dalam contoh sebelumnya, Can*
digunakan sebagai salah satu nilai untuk parameter Properti untuk mengembalikan semua properti yang dimulai dengan Can
. Ini termasuk CanPauseAndContinue, CanShutdown, dan CanStop.
Metode
Metode adalah tindakan yang dapat diambil. Gunakan parameter MemberType untuk mempersempit hasil Get-Member
untuk hanya menampilkan metode untuk 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...
Seperti yang Anda lihat, ada banyak metode. Metode Hentikan dapat digunakan untuk menghentikan layanan Windows.
(Get-Service -Name w32time).Stop()
Sekarang untuk memverifikasi layanan waktu Windows memang telah dihentikan.
Get-Service -Name w32time
Status Name DisplayName
------ ---- -----------
Stopped w32time Windows Time
Saya jarang menemukan diri saya menggunakan metode, tetapi mereka adalah sesuatu yang perlu Anda waspadai. Ada kalanya Anda akan menemukan Get-*
perintah tanpa perintah yang sesuai untuk memodifikasi item tersebut.
Seringkali, metode dapat digunakan untuk melakukan tindakan yang memodifikasinya. Get-SqlAgentJob
Cmdlet dalam modul SqlServer PowerShell adalah contoh yang baik dari ini. Modul diinstal sebagai bagian dari SQL Server Management Studio (SMSS). Tidak ada cmdlet yang Set-*
sesuai, tetapi metode dapat digunakan untuk menyelesaikan tugas yang sama.
Alasan lain untuk menyadari metode adalah bahwa banyak pemula mengasumsikan perubahan destruktif tidak dapat dilakukan dengan Get-*
perintah. Tetapi mereka memang dapat menyebabkan masalah serius jika digunakan secara tidak pantas.
Opsi yang lebih baik adalah menggunakan cmdlet untuk melakukan tindakan jika ada. Lanjutkan dan mulai layanan Windows Time, kecuali kali ini gunakan cmdlet untuk memulai layanan.
Get-Service -Name w32time | Start-Service -PassThru
Status Name DisplayName
------ ---- -----------
Running w32time Windows Time
Secara default, Start-Service
tidak mengembalikan hasil apa pun seperti metode Get-Service
awal .
Tetapi salah satu manfaat menggunakan cmdlet adalah bahwa berkali-kali cmdlet menawarkan fungsionalitas tambahan yang tidak tersedia dengan metode . Dalam contoh sebelumnya, parameter PassThru digunakan. Ini menyebabkan cmdlet yang biasanya tidak menghasilkan output, untuk menghasilkan output.
Berhati-hatilah dengan asumsi tentang output cmdlet. Kita semua tahu apa yang terjadi ketika Anda berasumsi hal-hal. Saya akan mengambil informasi tentang proses PowerShell yang berjalan di komputer lingkungan lab Windows 10 saya.
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
Sekarang saya akan menyalurkan perintah yang sama ke 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...
Perhatikan bahwa ada lebih banyak properti yang tercantum daripada yang ditampilkan secara default. Sejumlah properti default yang ditampilkan tidak muncul sebagai properti saat melihat hasil Get-Member
. Ini karena banyak nilai yang ditampilkan, seperti NPM(K)
, , PM(K)
WS(K)
, dan CPU(s)
, adalah properti terhitung. Untuk menentukan nama properti aktual, perintah harus disalurkan ke Get-Member
.
Jika perintah tidak menghasilkan output, perintah tidak dapat disalurkan ke Get-Member
. Karena Start-Service
tidak menghasilkan output secara default, itu menghasilkan kesalahan ketika Anda mencoba untuk menyalurkannya ke 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
Parameter PassThru dapat ditentukan dengan Start-Service
cmdlet membuatnya menghasilkan output, yang kemudian disalurkan tanpa Get-Member
kesalahan.
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();
Untuk disalurkan ke Get-Member
, perintah harus menghasilkan output berbasis objek.
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
menulis langsung ke host PowerShell, tetapi tidak menghasilkan output berbasis objek untuk alur. Jadi tidak dapat disalurkan ke Get-Member
.
Direktori Aktif
Catatan
Alat Administrasi Server Jarak Jauh yang tercantum di bagian persyaratan bab ini diperlukan untuk menyelesaikan bagian ini. Juga, seperti yang disebutkan dalam pengenalan buku ini, komputer lingkungan lab Windows 10 Anda harus menjadi anggota domain lingkungan lab.
Gunakan Get-Command
dengan parameter Modul untuk menentukan perintah apa yang ditambahkan sebagai bagian dari modul PowerShell ActiveDirectory saat alat administrasi server jarak jauh diinstal.
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...
...
Total 147 perintah ditambahkan sebagai bagian dari modul ActiveDirectory PowerShell. Beberapa perintah dari perintah ini hanya mengembalikan sebagian properti yang tersedia secara default.
Apakah Anda melihat sesuatu yang berbeda tentang nama perintah dalam modul ini? Bagian kata benda dari perintah memiliki awalan AD. Ini umum untuk dilihat pada perintah sebagian besar modul. Awalan dirancang untuk membantu mencegah konflik penamaan.
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;}
Bahkan jika Anda hanya samar-samar terbiasa dengan Direktori Aktif, Anda mungkin menyadari bahwa akun pengguna memiliki lebih banyak properti daripada yang ditunjukkan dalam contoh ini.
Get-ADUser
Cmdlet memiliki parameter Properti yang digunakan untuk menentukan properti tambahan (non-default) yang ingin Anda kembalikan. Menentukan *
karakter kartubebas mengembalikan semuanya.
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...
Sekarang yang terlihat lebih seperti itu.
Dapatkah Anda memikirkan alasan mengapa properti akun pengguna Direktori Aktif akan sangat dibatasi secara default? Bayangkan jika Anda mengembalikan setiap properti untuk setiap akun pengguna di lingkungan Direktori Aktif produksi Anda. Pikirkan penurunan performa yang dapat Anda sebabkan, tidak hanya ke pengendali domain itu sendiri, tetapi juga ke jaringan Anda. Sangat diragukan bahwa Anda akan benar-benar membutuhkan setiap properti. Mengembalikan semua properti untuk satu akun pengguna dapat diterima dengan sempurna saat Anda mencoba menentukan properti apa yang ada.
Tidak jarang menjalankan perintah berkali-kali ketika membuat prototipe. Jika Anda akan melakukan beberapa kueri besar, kueri sekali dan simpan hasilnya dalam variabel. Kemudian bekerja dengan konten variabel alih-alih berulang kali menggunakan beberapa kueri mahal.
$Users = Get-ADUser -Identity mike -Properties *
Gunakan konten variabel alih-alih $Users
menjalankan perintah sebelumnya berkali-kali.
Perlu diingat bahwa konten variabel tidak diperbarui saat perubahan dilakukan pada pengguna tersebut di Direktori Aktif.
Anda dapat menyalurkan $Users
variabel untuk Get-Member
menemukan properti yang tersedia.
$Users | Get-Member
Kemudian pilih properti individual dengan mempipa $Users
ke Select-Object
, semua tanpa harus mengkueri Direktori Aktif lebih dari satu kali.
$Users | Select-Object -Property Name, LastLogonDate, LastBadPasswordAttempt
Jika Anda akan mengkueri Direktori Aktif lebih dari sekali, gunakan parameter Properti untuk menentukan properti non-default yang Anda inginkan.
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
Ringkasan
Dalam bab ini, Anda telah mempelajari cara menentukan jenis objek apa yang dihasilkan perintah, cara menentukan properti dan metode apa yang tersedia untuk perintah, dan cara bekerja dengan perintah yang membatasi properti yang dikembalikan secara default.
Tinjauan
- Jenis objek apa yang
Get-Process
dihasilkan cmdlet? - Bagaimana Anda menentukan properti yang tersedia untuk perintah?
- Jika ada perintah untuk mendapatkan sesuatu tetapi tidak untuk mengatur hal yang sama, apa yang harus Anda periksa?
- Bagaimana perintah tertentu yang tidak menghasilkan output secara default dibuat untuk menghasilkan output?
- Jika Anda akan bekerja dengan hasil perintah yang menghasilkan sejumlah besar output, apa yang harus Anda pertimbangkan untuk melakukan?
Bacaan yang Disarankan
Saran dan Komentar
https://aka.ms/ContentUserFeedback.
Segera hadir: Sepanjang tahun 2024 kami akan menghentikan penggunaan GitHub Issues sebagai mekanisme umpan balik untuk konten dan menggantinya dengan sistem umpan balik baru. Untuk mengetahui informasi selengkapnya, lihat:Kirim dan lihat umpan balik untuk