不是所有 .NET Framework 类都可使用 New-Object 来创建。 例如,如果你尝试使用 New-Object 创建 System.Environment 或 System.Math 对象,你将收到以下错误消息:

PS C:\Users\maxsu> New-Object System.Environment
New-Object : 找不到构造函数。找不到类型 System.Environment 的相应构造函数。
所在位置 行:1 字符: 1
+ New-Object System.Environment
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand

之所以发生这些错误,是因为无法从这些类创建新的对象。 这些类是不更改状态的方法和属性的引用库。 你无需创建这些类,只需要使用它们。 这样的类和方法称为静态类,因为它们不会被创建、销毁或更改。 为了明确这一点,我们将提供静态类的使用示例。

1.使用 System.Environment 获取环境数据

通常,在 Windows PowerShell 中使用对象的第一步是使用 Get-Member 找出其所包含的成员。 使用静态类,进程会稍有不同,因为实际类不是对象。

引用静态的 System.Environment 类

可以通过使用方括号将类名称括起来以引用静态类。 例如,可以通过在括号内键入名称来引用 System.Environment。 执行此操作会显示某些泛型类型的信息:

PS> [System.Environment]

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    Environment                              System.Object

注意:正如我们之前提到的,当你使用 New-Object 时,Windows PowerShell 会 使用 New-Object.时输入名称。 使用被括号括起来的类型名称时也会发生同样的情况,因此可以将 [System.Environment] 指定为 [Environment] 。

System.Environment 类包含关于当前进程工作环境的一般信息,如果是在 Windows PowerShell 内工作,该进程为 powershell.exe。
如果尝试通过键入 [System.Environment] | Get-Member 来查看此类的详细信息,对象类型将报告为 System.RuntimeType,而不是 System.Environment:

PS C:\Users\maxsu> [System.Environment] | Get-Member


   TypeName:System.RuntimeType

Name                           MemberType Definition
----                           ---------- ----------
AsType                         Method     type AsType()
Clone                          Method     System.Object Clone(), System.Object ICloneable.Clone()
Equals                         Method     bool Equals(System.Object obj), bool Equals(type o), bool _MemberInfo.Equa...
FindInterfaces                 Method     type[] FindInterfaces(System.Reflection.TypeFilter filter, System.Object f...
FindMembers                    Method     System.Reflection.MemberInfo[] FindMembers(System.Reflection.MemberTypes m...
GetArrayRank                   Method     int GetArrayRank(), int _Type.GetArrayRank()
GetConstructor                 Method     System.Reflection.ConstructorInfo GetConstructor(System.Reflection.Binding...
GetConstructors                Method     System.Reflection.ConstructorInfo[] GetConstructors(System.Reflection.Bind...
GetCustomAttributes            Method     System.Object[] GetCustomAttributes(bool inherit), System.Object[] GetCust...
GetCustomAttributesData        Method     System.Collections.Generic.IList[System.Reflection.CustomAttributeData] Ge...

若要使用 Get-Member 查看静态成员,请指定 Static 参数:

PS C:\Users\maxsu> [System.Environment] | Get-Member -Static


   TypeName:System.Environment

Name                       MemberType Definition
----                       ---------- ----------
Equals                     Method     static bool Equals(System.Object objA, System.Object objB)
Exit                       Method     static void Exit(int exitCode)
ExpandEnvironmentVariables Method     static string ExpandEnvironmentVariables(string name)
FailFast                   Method     static void FailFast(string message), static void FailFast(string message, Sys...
GetCommandLineArgs         Method     static string[] GetCommandLineArgs()
GetEnvironmentVariable     Method     static string GetEnvironmentVariable(string variable), static string GetEnviro...
GetEnvironmentVariables    Method     static System.Collections.IDictionary GetEnvironmentVariables(), static System...
GetFolderPath              Method     static string GetFolderPath(System.Environment+SpecialFolder folder), static s...
GetLogicalDrives           Method     static string[] GetLogicalDrives()
ReferenceEquals            Method     static bool ReferenceEquals(System.Object objA, System.Object objB)
SetEnvironmentVariable     Method     static void SetEnvironmentVariable(string variable, string value), static void...
CommandLine                Property   static string CommandLine {get;}
CurrentDirectory           Property   static string CurrentDirectory {get;set;}
CurrentManagedThreadId     Property   static int CurrentManagedThreadId {get;}
ExitCode                   Property   static int ExitCode {get;set;}
HasShutdownStarted         Property   static bool HasShutdownStarted {get;}
Is64BitOperatingSystem     Property   static bool Is64BitOperatingSystem {get;}
Is64BitProcess             Property   static bool Is64BitProcess {get;}
MachineName                Property   static string MachineName {get;}
NewLine                    Property   static string NewLine {get;}
OSVersion                  Property   static System.OperatingSystem OSVersion {get;}
ProcessorCount             Property   static int ProcessorCount {get;}
StackTrace                 Property   static string StackTrace {get;}
SystemDirectory            Property   static string SystemDirectory {get;}
SystemPageSize             Property   static int SystemPageSize {get;}
TickCount                  Property   static int TickCount {get;}
UserDomainName             Property   static string UserDomainName {get;}
UserInteractive            Property   static bool UserInteractive {get;}
UserName                   Property   static string UserName {get;}
Version                    Property   static version Version {get;}
WorkingSet                 Property   static long WorkingSet {get;}

现在我们可以从 System.Environment 选择要查看的属性。

2.显示 System.Environment 的静态属性

System.Environment 的属性也是静态的,并且必须使用与常规属性不同的方式进行指定。 我们使用 :: 向 Windows PowerShell 指示我们要使用静态方法或属性。 若要查看用于启动 Windows PowerShell 的命令,我们通过键入以下内容来检查 CommandLine 属性:

PS C:\Users\maxsu> [System.Environment]::Commandline\n"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"

若要检查操作系统版本,通过键入以下内容显示 OSVersion 属性:

PS C:\Users\maxsu> [System.Environment]::OSVersion

Platform ServicePack Version      VersionString
-------- ----------- -------      -------------
 Win32NT             10.0.18362.0 Microsoft Windows NT 10.0.18362.0

我们可以通过显示 HasShutdownStarted 属性来检查计算机是否处于关机进程中:

PS C:\Users\maxsu> [System.Environment]::HasShutdownStarted
False

3.使用 System.Math 做数学运算

System.Math 静态类可用于执行某些数学运算。 System.Math 的大多数重要成员是方法,我们可以用过使用 Get-Member 来显示它们。

注: System.Math 的一些方法具有相同的名称,但可以按其参数的类型对其进行区分。

键入以下内容来列出 System.Math 类的方法。

PS C:\Users\maxsu> [System.Math] | Get-Member -Static -MemberType Methods


   TypeName:System.Math

Name            MemberType Definition
----            ---------- ----------
Abs             Method     static sbyte Abs(sbyte value), static int16 Abs(int16 value), static int Abs(int value), ...
Acos            Method     static double Acos(double d)
Asin            Method     static double Asin(double d)
Atan            Method     static double Atan(double d)
Atan2           Method     static double Atan2(double y, double x)
BigMul          Method     static long BigMul(int a, int b)
Ceiling         Method     static decimal Ceiling(decimal d), static double Ceiling(double a)
Cos             Method     static double Cos(double d)
Cosh            Method     static double Cosh(double value)
DivRem          Method     static int DivRem(int a, int b, [ref] int result), static long DivRem(long a, long b, [re...
Equals          Method     static bool Equals(System.Object objA, System.Object objB)
Exp             Method     static double Exp(double d)
Floor           Method     static decimal Floor(decimal d), static double Floor(double d)
IEEERemainder   Method     static double IEEERemainder(double x, double y)
Log             Method     static double Log(double a, double newBase), static double Log(double d)
Log10           Method     static double Log10(double d)
Max             Method     static sbyte Max(sbyte val1, sbyte val2), static byte Max(byte val1, byte val2), static i...
Min             Method     static sbyte Min(sbyte val1, sbyte val2), static byte Min(byte val1, byte val2), static i...
Pow             Method     static double Pow(double x, double y)
ReferenceEquals Method     static bool ReferenceEquals(System.Object objA, System.Object objB)
Round           Method     static double Round(double value, int digits), static double Round(double value, System.M...
Sign            Method     static int Sign(sbyte value), static int Sign(int16 value), static int Sign(int value), s...
Sin             Method     static double Sin(double a)

这会显示多种数学方法。 以下是一个命令列表,展示了某些常用方法的示例:

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