Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
PowerShell è un linguaggio di scripting orientato agli oggetti. Rappresenta i dati e gli stati di sistema usando oggetti strutturati derivati da classi .NET definite in .NET Framework. Sfruttando .NET Framework, PowerShell offre l'accesso a varie funzionalità di sistema, tra cui file system, registro di sistema e classi WMI (Windows Management Instrumentation). PowerShell ha anche accesso alla libreria di classi .NET Framework, che contiene una vasta raccolta di classi che è possibile usare per sviluppare script di PowerShell affidabili.
In PowerShell ogni elemento o stato è un'istanza di un oggetto che può essere esplorato e modificato.
Il Get-Member cmdlet è uno degli strumenti principali forniti da PowerShell per l'individuazione degli oggetti, che rivela le caratteristiche di un oggetto. Questo capitolo illustra come PowerShell sfrutta gli oggetti e come è possibile individuare e modificare questi oggetti per semplificare gli script e gestire i sistemi in modo più efficiente.
Prerequisiti
Per seguire gli esempi specifici in questo capitolo, assicurarsi che il computer dell'ambiente lab faccia parte del dominio active Directory dell'ambiente lab. È anche necessario installare il modulo PowerShell di Active Directory in bundle con Strumenti di amministrazione remota del server di Windows. Se usi Windows 10 build 1809 o versione successiva, incluso Windows 11, puoi installare Strumenti di amministrazione remota del server come funzionalità di Windows.
Nota
Active Directory non è supportato per le edizioni di Windows Home.
- Per informazioni sull'installazione di Strumenti di amministrazione remota del server, vedere Moduli di gestione Windows.
- Per le versioni precedenti di Windows, vedere Strumenti di amministrazione remota del server per Windows.
Get-Member
Get-Member fornisce informazioni dettagliate sugli oggetti, le proprietà e i metodi associati ai comandi di PowerShell. È possibile inviare tramite pipe qualsiasi comando di PowerShell che produce output basato su oggetti a Get-Member.
Quando si invia tramite pipe l'output di un comando a Get-Member, viene visualizzata la struttura dell'oggetto restituito dal comando, descrivendone in dettaglio le proprietà e i metodi.
- Proprietà: attributi di un oggetto.
- Metodi: le azioni che è possibile eseguire su un oggetto .
Per illustrare questo concetto, considerare la patente di un conducente come un'analogia. Come qualsiasi oggetto, la patente di guida ha proprietà, ad esempio il colore degli occhi, che in genere include blue e brown valori.
Al contrario, i metodi rappresentano le azioni che è possibile eseguire sull'oggetto . Ad esempio, Revoke è un metodo che il Dipartimento dei veicoli a motore può eseguire sulla patente di un conducente.
Proprietà
Per recuperare informazioni dettagliate sul servizio Ora di Windows nel sistema tramite PowerShell, usare il Get-Service cmdlet .
Get-Service -Name w32time
I risultati includono le proprietà Status, Name e DisplayName . La proprietà Status indica che il servizio è Running. Il valore della proprietà Name è w32timee il valore per la proprietà DisplayName è Windows Time.
Status Name DisplayName
------ ---- -----------
Running w32time Windows Time
Per elencare tutte le proprietà e i metodi disponibili per Get-Service, inviarlo tramite pipe a Get-Member.
Get-Service -Name w32time | Get-Member
I risultati mostrano che la prima riga contiene una parte di informazioni significative. TypeName identifica il tipo di oggetto restituito, che in questo esempio è un oggetto System.ServiceProcess.ServiceController . Questo nome viene spesso abbreviato nell'ultima parte di TypeName, ad esempio ServiceController, in questo esempio.
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();
Si noti che quando è stata inviata Get-Service tramite pipe a Get-Member, sono presenti più proprietà di quelle visualizzate per impostazione predefinita. Anche se queste proprietà aggiuntive non sono visualizzate per impostazione predefinita, è possibile selezionarle tramite pipe e Select-Object usando il parametro Property . Nell'esempio seguente vengono selezionate tutte le proprietà inviando tramite pipe i risultati di Get-Service a Select-Object e specificando il * carattere jolly come valore per il parametro Property .
Get-Service -Name w32time | Select-Object -Property *
Per impostazione predefinita, PowerShell restituisce quattro proprietà come tabella e cinque o più come elenco. Tuttavia, alcuni comandi applicano la formattazione personalizzata per eseguire l'override del numero predefinito di proprietà visualizzate in una tabella.
È possibile usare Format-Table e Format-List per eseguire manualmente l'override di queste impostazioni predefinite.
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 :
È anche possibile selezionare proprietà specifiche usando un elenco delimitato da virgole come valore del parametro Property .
Get-Service -Name w32time |
Select-Object -Property Status, Name, DisplayName, ServiceType
Status Name DisplayName ServiceType
------ ---- ----------- -----------
Running w32time Windows Time Win32OwnProcess, Win32ShareProcess
È possibile usare caratteri jolly quando si specificano nomi di proprietà con Select-Object.
Nell'esempio seguente usare Can* come uno dei valori per il parametro Property per restituire tutte le proprietà che iniziano con Can. Le proprietà includono CanPauseAndContinue, CanShutdown e CanStop.
Get-Service -Name w32time |
Select-Object -Property Status, DisplayName, Can*
Si noti che sono elencate più proprietà di quelle visualizzate per impostazione predefinita.
Status : Running
DisplayName : Windows Time
CanPauseAndContinue : False
CanShutdown : True
CanStop : True
Metodi
I metodi sono azioni che è possibile eseguire su un oggetto . Usare il parametro MemberType per limitare i risultati di Get-Member per visualizzare solo i metodi per Get-Service.
Get-Service -Name w32time | Get-Member -MemberType Method
Come si può notare, esistono diversi metodi.
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...
È possibile usare il metodo Stop per arrestare un servizio Windows. È necessario eseguire questo comando da una sessione di PowerShell con privilegi elevati.
(Get-Service -Name w32time).Stop()
Eseguire una query sullo stato del servizio Ora di Windows per verificare che sia stato arrestato.
Get-Service -Name w32time
Status Name DisplayName
------ ---- -----------
Stopped w32time Windows Time
È possibile usare metodi con moderazione, ma è consigliabile conoscerli. In alcuni casi, è possibile trovare Get-* comandi senza un comando corrispondente Set-* . Spesso è possibile trovare un metodo per eseguire un'azione Set-* in questo scenario. Il Get-SqlAgentJob cmdlet nel modulo SqlServer PowerShell è un esempio eccellente. Non esiste alcun cmdlet corrispondente Set-* , ma è possibile usare un metodo per completare la stessa attività. Per altre informazioni sul modulo SqlServer PowerShell e le istruzioni di installazione, vedere la panoramica di SQL Server PowerShell.
Un altro motivo per essere consapevoli dei metodi è che alcuni utenti di PowerShell presuppongono che non sia possibile apportare modifiche distruttive con Get-* i comandi, ma possono effettivamente causare gravi problemi se usati in modo improprio.
Un'opzione migliore consiste nell'usare un cmdlet dedicato, se presente, per eseguire un'azione. Ad esempio, usare il Start-Service cmdlet per avviare il servizio Ora di Windows.
Per impostazione predefinita, , Start-Servicecome il metodo Start di Get-Service, non restituisce alcun risultato.
Tuttavia, uno dei vantaggi dell'uso di un cmdlet è che spesso offre funzionalità aggiuntive che non sono disponibili con un metodo.
Nell'esempio seguente usare il parametro PassThru , che causa la generazione dell'output da parte di un cmdlet che in genere non produce output.
Poiché PowerShell non partecipa a User Controllo di accesso (UAC), è necessario eseguire comandi che richiedono l'elevazione dei privilegi, ad esempio Start-Service, da una sessione di PowerShell con privilegi elevati.
Get-Service -Name w32time | Start-Service -PassThru
Status Name DisplayName
------ ---- -----------
Running w32time Windows Time
Nota
Quando si mettono in uso i cmdlet di PowerShell, è importante evitare di fare ipotesi sull'output.
Per recuperare informazioni sul processo di PowerShell in esecuzione nel computer dell'ambiente lab, usare il 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
Per determinare le proprietà disponibili, inviare tramite pipe Get-Process a Get-Member.
Get-Process -Name powershell | Get-Member
Quando si usa il Get-Process comando , è possibile notare che alcune proprietà visualizzate per impostazione predefinita non sono presenti quando si visualizzano i risultati di Get-Member. Questo comportamento è dovuto al fatto che diversi valori visualizzati per impostazione predefinita, ad esempio NPM(K), PM(K)WS(K), e CPU(s), sono proprietà calcolate. È necessario inviare tramite pipe i comandi per Get-Member determinare i nomi effettivi delle proprietà.
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...
Non è possibile inviare tramite pipe un comando a Get-Member che non genera output. Poiché Start-Service non produce output per impostazione predefinita, il tentativo di inviarlo tramite pipe a Get-Member genera un errore.
Start-Service -Name w32time | Get-Member
Nota
Per essere inviato tramite pipe a Get-Member, un comando deve produrre un output basato su oggetti.
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
Per evitare questo errore, specificare il parametro PassThru con Start-Service. Come accennato in precedenza, l'aggiunta del parametro PassThru causa un cmdlet che in genere non produce output per generare l'output.
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 è progettato per visualizzare l'output direttamente nell'host di PowerShell e non produce output basato su oggetti. Di conseguenza, non è possibile inviare tramite pipe l'output a Get-Member, che richiede input basato su oggetti.
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
Conoscere il tipo di oggetto prodotto da un comando consente di cercare comandi che accettano tale tipo di oggetto come input.
Get-Command -ParameterType ServiceController
I comandi seguenti accettano un oggetto ServiceController tramite l'input della pipeline o del parametro.
CommandType Name Version
----------- ---- -------
Cmdlet Get-Service 3.1.0.0
Cmdlet Restart-Service 3.1.0.0
Cmdlet Resume-Service 3.1.0.0
Cmdlet Set-Service 3.1.0.0
Cmdlet Start-Service 3.1.0.0
Cmdlet Stop-Service 3.1.0.0
Cmdlet Suspend-Service 3.1.0.0
Active Directory
Nota
Come indicato nel capitolo prerequisiti, assicurarsi di avere installato Strumenti di amministrazione remota del server per questa sezione. Inoltre, il computer dell'ambiente lab deve essere membro del dominio active Directory dell'ambiente lab.
Per identificare i comandi aggiunti al modulo Di PowerShell activeDirectory dopo l'installazione di Strumenti di amministrazione remota del server, usare in combinazione con il Get-Command. Nell'esempio seguente sono elencati tutti i comandi disponibili nel modulo ActiveDirectory .
Get-Command -Module ActiveDirectory
Il modulo Di PowerShell ActiveDirectory ha aggiunto un totale di 147 comandi.
Si è osservata la convenzione di denominazione di questi comandi? I sostantivi nei nomi dei comandi sono preceduti da AD per evitare potenziali conflitti di denominazione con i comandi in altri moduli. Questo prefisso è una pratica comune tra i moduli di 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
...
Per impostazione predefinita, il Get-ADUser cmdlet recupera un set limitato di proprietà per gli oggetti utente e ne limita l'output ai primi 1.000 utenti. Questo vincolo è un'ottimizzazione delle prestazioni progettata per evitare di sovraccaricare Active Directory con un recupero eccessivo dei dati.
Get-ADUser -Identity mike | Get-Member -MemberType Properties
Anche se si ha solo una conoscenza di base di Active Directory, è possibile riconoscere che un account utente ha più proprietà di quelle mostrate nell'esempio.
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;}
Il Get-ADUser cmdlet include un parametro Properties per specificare proprietà aggiuntive oltre le impostazioni predefinite che si desidera recuperare. Per restituire tutte le proprietà, usare il * carattere jolly come valore del parametro.
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...
La configurazione predefinita per il recupero delle proprietà dell'account utente di Active Directory è intenzionalmente limitata per evitare problemi di prestazioni. Il tentativo di restituire ogni proprietà per ogni account utente nell'ambiente Active Directory di produzione potrebbe compromettere gravemente le prestazioni dei controller di dominio e della rete. In genere, sono necessarie solo proprietà specifiche per determinati utenti. Tuttavia, la restituzione di tutte le proprietà per un singolo utente è ragionevole quando si identificano le proprietà disponibili.
Non è insolito eseguire un comando più volte durante la creazione di prototipi. Se si prevede di eseguire una query a elevato utilizzo di risorse durante la creazione di prototipi di un comando, è consigliabile eseguirla una sola volta e archiviare i risultati in una variabile. È quindi possibile usare il contenuto della variabile in modo più efficiente rispetto all'esecuzione ripetuta di una query a elevato utilizzo di risorse.
Ad esempio, il comando seguente recupera tutte le proprietà per un account utente e archivia i risultati in una variabile denominata $Users. Usare il contenuto della $Users variabile anziché eseguire il Get-ADUser comando più volte. Tenere presente che il contenuto della variabile non viene aggiornato automaticamente quando le informazioni di un utente cambiano in Active Directory.
$Users = Get-ADUser -Identity mike -Properties *
È possibile esplorare le proprietà disponibili eseguendo il piping della $Users variabile in Get-Member.
$Users | Get-Member -MemberType Properties
Per visualizzare proprietà specifiche, ad esempio Name, LastLogonDate e LastBadPasswordAttempt, inviare tramite pipe la $Users variabile a Select-Object. Questo metodo visualizza le proprietà desiderate e i relativi valori in base al contenuto della $Users variabile, eliminando la necessità di più query in Active Directory. Si tratta di un approccio più efficiente delle risorse rispetto all'esecuzione ripetuta del Get-ADUser comando.
$Users | Select-Object -Property Name, LastLogonDate, LastBadPasswordAttempt
Quando si esegue una query in Active Directory, filtrare i dati nell'origine usando il parametro Properties di Get-ADUser per restituire solo le proprietà necessarie.
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
Riepilogo
In questo capitolo si è appreso come determinare il tipo di oggetto prodotto da un comando, quali proprietà e metodi sono disponibili per un comando e come usare i comandi che limitano le proprietà restituite per impostazione predefinita.
Revisione
- Quale tipo di oggetto produce il cmdlet
Get-Process? - Come è possibile determinare quali sono le proprietà disponibili per un comando?
- Cosa è necessario verificare se esiste un comando per ottenere un elemento ma non per impostare la stessa cosa?
- Come possono essere eseguiti alcuni comandi che non restituiscono output per impostazione predefinita per generare l'output?
- Cosa è consigliabile considerare quando si crea un prototipo di un comando che produce una grande quantità di output?
Riferimenti
- get-member
- Visualizzazione della struttura degli oggetti (Get-Member)
- riguardo_agli_Oggetti
- riguardo_Proprietà
- sui_Metodi
- Nessun cmdlet di PowerShell per avviare o arrestare un elemento? Non dimenticare di verificare la presenza di metodi nei cmdlet Get
Passaggi successivi
Nel capitolo 4, imparerai a conoscere le espressioni a una riga e la pipeline.