Classes no Windows PowerShell

Quem já me viu definindo a sintaxe do Windows PowerShell provavelmente já me ouviu falar “PowerShell é igualzinho C#, mas sem classes”.

Pois bem. Eu estava errado. Eu já sabia que era possível criar assemblies manualmente e importar no PowerShell dinamicamente, mas o que eu não sabia é que ele já suporta isso nativamente, sem precisar compilar absolutamente nada. Isso tudo graças ao comando Add-Type, que cria classes dinamicamente para que você possa usar depois normalmente com o comando new-object.

Vejam um trecho do que o comando get-help add-type –detailed retorna:

NAME
    Add-Type
SYNOPSIS
    Adds a .NET type (a class) to a Windows PowerShell session.
DETAILED DESCRIPTION
    The Add-Type cmdlet lets you define a .NET class in your Windows PowerShell session. You can th
    en instantiate objects (by using the New-Object cmdlet) and use the objects, just as you would
    use any .NET object.  If you add an Add-Type command to your Windows PowerShell profile, the cl
    ass will be available in all Windows PowerShell sessions.
    You can specify the type by specifying an existing assembly or source code files, or you can sp
    ecify source code in line or saved in a variable. You can even specify only a method and Add-Ty
    pe will define and generate the class. You can use this feature to make Platform Invoke (P/Invo
    ke) calls to unmanaged functions in Windows PowerShell. If you specify source code, Add-Type co
    mpiles the specified source code and generates an in-memory assembly that contains the new .NET
     types.
    You can use the parameters of Add-Type to specify an alternate language and compiler (CSharp is
     the default), compiler options, assembly dependencies, the class namespace, and the names of t
    he type and the resulting assembly.

    -------------------------- EXAMPLE 1 --------------------------
    C:\PS>$source = @"
    public class BasicTest
    {
        public static int Add(int a, int b)
        {
            return (a + b);
        }
        public int Multiply(int a, int b)
        {
            return (a * b);
        }
    }
    "@
    C:\PS> Add-Type -TypeDefinition $source
    C:\PS> [BasicTest]::Add(4, 3)
    C:\PS> $basicTestObject = New-Object BasicTest
    C:\PS> $basicTestObject.Multiply(5, 2)
    These commands adds the BasicTest class to the session by specifying source code that is stored
     in a variable. The type has a static method called Add and a non-static method called Multiply
    .
    The first command stores the source code for the class in the $source variable.
    The second command uses the Add-Type cmdlet to add the class to the session. Because it is usin
    g inline source code, the command uses the TypeDefinition parameter to specify the code in the
    $source variable.
    The remaining commands use the new class.
    The third command calls the Add static method of the BasicTest class. It uses the double-colon
    characters (::) to specify a static member of the class.
    The fourth command uses the New-Object cmdlet to instantiate an instance of the BasicTest class
    . It saves the new object in the $basicTestObject variable.
    The fifth command uses the Multiply method of $basicTestObject.
    -------------------------- EXAMPLE 2 --------------------------
    C:\PS>[BasicTest] | get-member
    C:\PS> [BasicTest] | get-member -static
    C:\PS> $basicTestObject | get-member
    C:\PS> [BasicTest] | get-member
       TypeName: System.RuntimeType
    Name                           MemberType Definition
    ----                           ---------- ----------
    Clone                          Method     System.Object Clone()
    Equals                         Method     System.Boolean Equals
    FindInterfaces                 Method     System.Type[] FindInt
    ...
    C:\PS> [BasicTest] | get-member -static
       TypeName: BasicTest
    Name            MemberType Definition
    ----            ---------- ----------
    Add             Method     static System.Int32 Add(Int32 a, Int32 b)
    Equals          Method     static System.Boolean Equals(Object objA,
    ReferenceEquals Method     static System.Boolean ReferenceEquals(Obj
    C:\PS> $basicTestObject | get-member
       TypeName: BasicTest
    Name        MemberType Definition
    ----        ---------- ----------
    Equals      Method     System.Boolean Equals(Object obj)
    GetHashCode Method     System.Int32 GetHashCode()
    GetType     Method     System.Type GetType()
    Multiply    Method     System.Int32 Multiply(Int32 a, Int32 b)
    ToString    Method     System.String ToString()
    Description
    -----------
    These commands use the Get-Member cmdlet to examine the objects that the Add-Type and New-Objec
    t cmdlets created in the previous example.
    The first command uses the Get-Member cmdlet to get the type and members of the BasicTest class
     that Add-Type added to the session. The Get-Member command reveals that it is a System.Runtime
    Type object, which is derived from the System.Object class.
    The second command uses the Static parameter of Get-Member to get the static properties and met
    hods of the BasicTest class. The output shows that the Add method is included.
    The third command uses Get-Member to get the members of the object stored in the $BasicTestObje
    ct variable. This was the object instance that was created by using the New-Object cmdlet with
    the $BasicType class.
    The output reveals that $basicTestObject is an instance of the BasicTest class and that it incl
    udes a member called Multiply.

Enfim... acho melhor definir o PowerShell hoje como um shell interativo de C#, da mesma forma que o Ruby tem o IRB.

Até a próxima!

Categorias dessa postagem:

Comentários