Search code examples
.netpowershell

Powershell GetType


I want to check is some type exist. For example:

Add-Type -TypeDefinition '
public class Test{
    public static int aaa(){
        return 1;
    }
}'

[test]::aaa() # 1

[type]::GetType('test') # empty

but GetType() not works for my 'test' type.


Solution

  • You can test if the type already exists with

    if (-not ('Test' -as [type])) {
    # or 
    # if (-not ([System.Management.Automation.PSTypeName]'Test').Type) {
        Add-Type -TypeDefinition '
        public class Test{
            public static int aaa(){
                return 1;
            }
        }'
    }
    

    I don't know why [type]::GetType('test') doesn't work though, but

    ("Test" -as [type])
    

    does work and returns either $null or

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