Uso de clases y métodos estáticos
No todas las clases de .NET Framework se pueden crear usando New-Object. Por ejemplo, si intenta crear un objeto System.Environment o System.Math con New-Object, obtendrá el siguiente error mensajes:
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
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
Estos errores ocurren porque no hay forma de crear un nuevo objeto a partir de estas clases. Estas clases son bibliotecas de referencia de métodos y propiedades que no cambian de estado. No es necesario crearlos, simplemente utilizarlos. Las clases y métodos como estos se denominan clases estáticas porque no se crean, destruyen ni modifican. Para dejar esto claro, proporcionaremos ejemplos que utilizan clases estáticas.
Obtener datos del entorno con System.Environment
Normalmente, el primer paso para trabajar con un objeto en Windows PowerShell es utilizar Get-Member para averiguar qué miembros contiene. Con las clases estáticas, el proceso es un poco diferente porque la clase real no es un objeto.
Refiriéndose a la clase estática System.Environment
Puede hacer referencia a una clase estática rodeando el nombre de la clase entre corchetes. Por ejemplo, puede hacer referencia a System.Environment escribiendo el nombre entre corchetes. Al hacerlo, se muestra información de tipo genérico:
[System.Environment]
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False Environment System.Object
Nota
Como mencionamos anteriormente, Windows PowerShell antepone automáticamente 'Sistema.' para escribir nombres cuando usa Nuevo-Objeto. Lo mismo sucede cuando se utiliza un nombre de tipo entre corchetes, por lo que puede especificar [System.Environment] como [Environment].
La clase System.Environment contiene información general sobre el entorno de trabajo para el proceso actual, que es powershell.exe cuando se trabaja en Windows PowerShell.
Si intenta ver detalles de esta clase escribiendo [System.Environment] | Get-Member, el tipo de objeto se informa como System.RuntimeType, no System.Environment:
[System.Environment] | Get-Member
TypeName: System.RuntimeType
Para ver miembros estáticos con Get-Member, especifique el parámetro Static:
[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
Ahora podemos seleccionar propiedades para ver desde System.Environment.
Mostrando propiedades estáticas de System.Environment
Las propiedades de System.Environment también son estáticas y deben especificarse de forma diferente a las propiedades normales. Usamos :: para indicarle a Windows PowerShell que queremos trabajar con un método o propiedad estática. Para ver el comando que se utilizó para iniciar Windows PowerShell, verificamos la propiedad CommandLine escribiendo:
[System.Environment]::Commandline
"C:\Program Files\Windows PowerShell\v1.0\powershell.exe"
Para verificar la versión del sistema operativo, muestre la propiedad OSVersion escribiendo:
[System.Environment]::OSVersion
Platform ServicePack Version VersionString
-------- ----------- ------- -------------
Win32NT Service Pack 2 5.1.2600.131072 Microsoft Windows...
Podemos comprobar si el ordenador está en proceso de apagarse mostrando la propiedad HasShutdownStarted:
[System.Environment]::HasShutdownStarted
False
Haciendo matemáticas con System.Math
La clase estática System.Math es útil para realizar algunas operaciones matemáticas. La clase incluye varios métodos útiles, que podemos mostrar usando Get-Member.
Nota
System.Math tiene varios métodos con el mismo nombre, pero se distinguen por el tipo de sus parámetros.
Escriba el siguiente comando para enumerar los métodos de la clase System.Math.
[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...
Esto muestra varios métodos matemáticos. Aquí hay una lista de comandos que demuestran cómo funcionan algunos de los métodos comunes:
[System.Math]::Sqrt(9)
3
[System.Math]::Pow(2,3)
8
[System.Math]::Floor(3.3)
3
[System.Math]::Floor(-3.3)
-4
[System.Math]::Ceiling(3.3)
4
[System.Math]::Ceiling(-3.3)
-3
[System.Math]::Max(2,7)
7
[System.Math]::Min(2,7)
2
[System.Math]::Truncate(9.3)
9
[System.Math]::Truncate(-9.3)
-9