how to assign MaxValue and MinValue to a variable in powershell

Viewed 42

I tried these assignment statements below but none of them works.

$max_value = Integer.MaxValue

$max_value = Int32.MaxValue

$max_value = int.MaxValue
1 Answers

Santiago Squarzon provided the crucial pointer:

# Equivalent of the following C# code: int.MaxValue or System.Int32.MaxValue
[int]::MaxValue 
  • [int] is a PowerShell type literal that refers to .NET's System.Int32 type, i.e. a signed, 32-bit integer.

  • :: is PowerShell's operator for accessing static type members (whereas . is used for instance members, as in C#).

Aside from requiring that literal type names be enclosed in [...], PowerShell's type literals have some non-obvious features:

  • Unlike in C#, case does not matter in PowerShell type literals. E.g., [system.io.fileinfo] can be used to refer to the System.IO.FileInfo type.

  • Analogous to C# providing short names for frequently used types - such as int for System.Int32 and string for System.String - PowerShell defines a range of short type names called type accelerators, listed in the conceptual about_Type_Accelerators help topic.

    • Case in point: as in C#, [int] refers to System.Int32, which you may therefore also reference as [System.Int32].
    • You can invoke .FullName on any given type literal to see the target type's full (namespace-qualified) name; e.g, [int].FullName returns string System.Int32. This relies on the fact that any type literal is itself an instance of the System.Type type.
  • Irrespective of type accelerators, you always have the option of omitting the System. component of a type's name, so that you may refer to System.Linq.Enumerable as just [Linq.Enumerable] instead of having to spell out [System.Linq.Enumerable], for instance.

  • In PowerShell version 5 and above (including PowerShell (Core) 7+), you may use a using namespace statement, which, analogous to C#'s using statement, allows you to refer to the types in the specified namespace by their mere name; e.g.:

     # Important:
     #  * Must be at the *start* of a file.
     #  * The System. part may NOT be omitted in this case.
     using namespace System.Linq
    
     [Enumerable]  # Short for: [System.Linq.Enumerable]
    

To learn more about type literals in PowerShell, including how to specify generic types, see the bottom section of this answer.

Related