Non è possibile utilizzare New-Object per creare tutte le classi .NET Framework. Ad esempio, se si tenta di creare un oggetto System.Environment o System.Math con New-Object, verranno restituiti i messaggi di errore seguenti:
PS> New-Object System.Environment New-Object : Constructor not found. Cannot find an appropriate constructor for type System.Environment. At line:1 char:11 + New-Object <<<< System.Environment PS> New-Object System.Math New-Object : Constructor not found. Cannot find an appropriate constructor for type System.Math. At line:1 char:11 + New-Object <<<< System.Math
Tali errori si verificano perché non è possibile utilizzare queste classi per creare un nuovo oggetto. Tali classi sono infatti librerie di riferimento di metodi e proprietà che non prevedono la modifica dello stato. Non devono essere create ma solo utilizzate. Classi e metodi di questo tipo vengono definite classi statiche perché non vengono create, eliminate definitivamente o modificate. Per chiarire questo concetto, verranno forniti esempi in cui vengono utilizzate classi statiche.
Recupero dei dati relativi all'ambiente con System.Environment
Per poter gestire un oggetto in Windows PowerShell, il primo passaggio consiste in genere nell'utilizzare Get-Member per individuare i membri in esso contenuti. Con le classi statiche il processo è leggermente diverso perché la classe effettiva non è costituita da un oggetto.
Aggiunta di un riferimento alla classe statica System.Environment
È possibile fare riferimento a una classe statica racchiudendo il nome della classe tra parentesi quadre. È ad esempio possibile fare riferimento a System.Environment digitandone il nome tra parentesi quadre. In tal modo verranno visualizzate alcune informazioni generiche sul tipo:
PS> [System.Environment] IsPublic IsSerial Name BaseType -------- -------- ---- -------- True False Environment System.Object
Nota | |
Come spiegato in precedenza, quando si utilizza New-Object in Windows PowerShell viene automaticamente aggiunto 'System.' all'inizio dei nomi di tipo. Lo stesso comportamento viene applicato quando si utilizza un nome di tipo tra parentesi quadre, pertanto sarà possibile specificare [System.Environment] come [Environment]. |
La classe System.Environment contiene informazioni di carattere generale sull'ambiente di lavoro del processo corrente, che corrisponde a powershell.exe quando si opera in Windows PowerShell.
Se si tenta di visualizzare i dettagli di questa classe digitando [System.Environment] | Get-Member, il tipo dell'oggetto restituito sarà System.RuntimeType e non System.Environment:
PS> [System.Environment] | Get-Member TypeName: System.RuntimeType
Per visualizzare i membri statici con Get-Member, specificare il parametro Static :
PS> [System.Environment] | Get-Member -Static TypeName: System.Environment Name MemberType Definition ---- ---------- ---------- Equals Method static System.Boolean Equals(Object ob... Exit Method static System.Void Exit(Int32 exitCode) ... CommandLine Property static System.String CommandLine {get;} CurrentDirectory Property static System.String CurrentDirectory ... ExitCode Property static System.Int32 ExitCode {get;set;} HasShutdownStarted Property static System.Boolean HasShutdownStart... MachineName Property static System.String MachineName {get;} NewLine Property static System.String NewLine {get;} OSVersion Property static System.OperatingSystem OSVersio... ProcessorCount Property static System.Int32 ProcessorCount {get;} StackTrace Property static System.String StackTrace {get;} SystemDirectory Property static System.String SystemDirectory {... TickCount Property static System.Int32 TickCount {get;} UserDomainName Property static System.String UserDomainName {g... UserInteractive Property static System.Boolean UserInteractive ... UserName Property static System.String UserName {get;} Version Property static System.Version Version {get;} WorkingSet Property static System.Int64 WorkingSet {get;} TickCount ExitCode
A questo punto sarà possibile selezionare le proprietà da visualizzare da System.Environment.
Visualizzazione delle proprietà statiche di System.Environment
Anche le proprietà di System.Environment sono statiche e devono essere specificate in modo diverso rispetto a quelle normali. Per indicare a Windows PowerShell che si desidera operare con una proprietà o un metodo statico viene utilizzato ::. Per visualizzare il comando utilizzato per avviare Windows PowerShell, verrà verificata la proprietà CommandLine digitando:
PS> [System.Environment]::Commandline "C:\Program Files\Windows PowerShell\v1.0\powershell.exe"
Per verificare la versione del sistema operativo, visualizzare la proprietà OSVersion digitando:
PS> [System.Environment]::OSVersion Platform ServicePack Version VersionString -------- ----------- ------- ------------- Win32NT Service Pack 2 5.1.2600.131072 Microsoft Window...
Per verificare se l'arresto del computer è stato avviato, è possibile visualizzare la proprietà HasShutdownStarted :
PS> [System.Environment]::HasShutdownStarted False
Esecuzione di operazioni matematiche con System.Math
La classe statica System.Math è utile per eseguire alcune operazioni matematiche. I membri importanti di System.Math sono costituiti principalmente da metodi visualizzabili tramite Get-Member.
Nota | |
Per System.Math sono disponibili diversi metodi caratterizzati dallo stesso nome, ma distinguibili in base al tipo dei relativi parametri. |
Digitare il comando seguente per visualizzare l'elenco dei metodi della classe System.Math.
PS> [System.Math] | Get-Member -Static -MemberType Methods TypeName: System.Math Name MemberType Definition ---- ---------- ---------- Abs Method static System.Single Abs(Single value), static Sy... Acos Method static System.Double Acos(Double d) Asin Method static System.Double Asin(Double d) Atan Method static System.Double Atan(Double d) Atan2 Method static System.Double Atan2(Double y, Double x) BigMul Method static System.Int64 BigMul(Int32 a, Int32 b) Ceiling Method static System.Double Ceiling(Double a), static Sy... Cos Method static System.Double Cos(Double d) Cosh Method static System.Double Cosh(Double value) DivRem Method static System.Int32 DivRem(Int32 a, Int32 b, Int3... Equals Method static System.Boolean Equals(Object objA, Object ... Exp Method static System.Double Exp(Double d) Floor Method static System.Double Floor(Double d), static Syst... IEEERemainder Method static System.Double IEEERemainder(Double x, Doub... Log Method static System.Double Log(Double d), static System... Log10 Method static System.Double Log10(Double d) Max Method static System.SByte Max(SByte val1, SByte val2), ... Min Method static System.SByte Min(SByte val1, SByte val2), ... Pow Method static System.Double Pow(Double x, Double y) ReferenceEquals Method static System.Boolean ReferenceEquals(Object objA... Round Method static System.Double Round(Double a), static Syst... Sign Method static System.Int32 Sign(SByte value), static Sys... Sin Method static System.Double Sin(Double a) Sinh Method static System.Double Sinh(Double value) Sqrt Method static System.Double Sqrt(Double d) Tan Method static System.Double Tan(Double a) Tanh Method static System.Double Tanh(Double value) Truncate Method static System.Decimal Truncate(Decimal d), static...
Verranno visualizzati diversi metodi matematici. Di seguito è riportato un elenco di comandi che illustrano il funzionamento di alcuni metodi comuni:
PS> [System.Math]::Sqrt(9) 3 PS> [System.Math]::Pow(2,3) 8 PS> [System.Math]::Floor(3.3) 3 PS> [System.Math]::Floor(-3.3) -4 PS> [System.Math]::Ceiling(3.3) 4 PS> [System.Math]::Ceiling(-3.3) -3 PS> [System.Math]::Max(2,7) 7 PS> [System.Math]::Min(2,7) 2 PS> [System.Math]::Truncate(9.3) 9 PS> [System.Math]::Truncate(-9.3) -9