≡ Menu

C# typeof equivalent in PowerShell

Those who are good with C# knows what typeof does. Basically is used for finding the type data of a given variable or object. How do we do this when it comes to PowerShell? Is there any equivalent keyword for typeof in PowerShell? Let us find out.

PowerShell implements typeof in little different way. Instead of using the typeof keyword like in C#, the PowerShell provides a method called GetType() for each variable or object to find its type. For example, if you want to find data type of a variable called $username, you can know it by calling $username.gettype().

$username = “techibee”

$username.GetType()

PowerShell Typeof equivalent

You can also check if the returned type is a string, integer or some other data type by comparing it as shown below.

$username = “techibee”

$username.GetType() -eq [string]

$age = 12

$age.GetType() -eq [int32]

$age.GetType() -eq [string]

PowerShell typeof

Do you know any other case where PowerShell’s Gettype() cannot replace typeof keyword in C#? Please post in comments section.

Comments on this entry are closed.

  • Anonymous October 30, 2017, 10:01 pm

    $x=(Get-Acl -Path $Path).GetOwner([System.Security.Principal.NTAccount]) works

    $x=(Get-Acl -Path $Path).GetOwner([System.Security.Principal.NTAccount].GetType()) does not work.

    • Wintel Rocks November 12, 2017, 9:41 pm

      Curious to know what exactly you are trying to achieve… I will be able to comment better if you provide the details.

  • Joseph July 26, 2018, 7:16 pm

    in C# i would do this:
    Type t = typeof(System.DirectoryServices.AccountManagement.UserPrincipal);

    i can get the same in PowerShell like this:
    $t = [System.Type]([System.DirectoryServices.AccountManagement.UserPrincipal])

    This seems to return the System.Type like the C# typeof().

    In Anonymous’ example, the GetOwner method expect a target type to be passed. This first statement seems to implicitly coerce the input as typeof(), while the second statement would have passed an object of System.Type. The exception is expecting a Type that is a subclass of a specific Type like: System.Security.Principal.IdentityReference