http://blogs.clariusconsulting.net/kzu

Daniel Cazzulino's Blog

Go Back to
kzu′s Latest post

How to use C# typeof in Powershell

Have you ever missed C#’s “typeof” while working with PowerShell?

PS C:\> [System.Type]::GetType("System.Enum") 

IsPublic IsSerial Name                                     BaseType-------- -------- ----                                     --------True     True     Enum                                     System.ValueType 

PS C:\> typeof System.Enum 

IsPublic IsSerial Name                                     BaseType-------- -------- ----                                     --------True     True     Enum                                     System.ValueType 

I know I do. So I created the following snap-in:

using System.Globalization;
using System.Management.Automation;

namespace Clarius.PowerShell
{
    [Cmdlet(VerbsCommon.Get, "Type")]
    public class GetTypeCommand : Cmdlet
    {
        private string typeName;

        [Parameter(Mandatory=true, Position=0, HelpMessageResourceId="Parameter_TypeName")]
        public string TypeName
        {
            get { return typeName; }
            set { typeName = value; }
        }

        protected override void ProcessRecord()
        {
            string name = typeName;
            if (name.StartsWith("[")) name = name.Substring(1);
            if (name.EndsWith("]")) name = name.Substring(0, name.Length - 1);

            WriteObject(new TypeNameConverter().ConvertFrom(name, typeof(Type), CultureInfo.CurrentCulture, true));
        }
    }
}

And after registering your snap-in you can add the following alias on your profile:

set-alias typeof Get-Type

And now you can use your beloved "typeof" passing just the type name.

Comments

2 Comments

  1. What is the TypeNameConverter class?

  2. At http://us.generation-nt.com/answer/typeof-powershell-help-66319982.html#66320042 Kevin Loo of Microsoft says you can also use the [] operator. Apparently it can be used both as a cast operator and the typeof operator, depending on where you put it in an expression.