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()
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]
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.
$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.
Curious to know what exactly you are trying to achieve… I will be able to comment better if you provide the details.
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