January 2nd, 2009

How To Write a Console Application in PowerShell with Add-Type

PowerShell Team
PowerShell Team

Windows PowerShell CTP3 has a lot of very cool things.  CTP2 introduced the Add-Type cmdlet, which allowed you to dynamically compile C# in PowerShell.  It was actually possible to use the CompilerParameters to Add-Type to make a console application, but it wasn’t particularly easy.  In CTP3, we’ve made this a lot easier to do.

There’s now an -OutputType parameter for Add-Type.  It can either output a Library (the default), a ConsoleApplication, or a WindowsApplication.  Check out this really quick "Hello World" program built using Add-Type.

Add-Type -OutputType ConsoleApplication -OutputAssembly HelloWorld.exe @"
using System;

public class MyProgram
{
    public static void Main(string[] args) {
        Console.WriteLine("Hello World");
    }
}
"@

Hope this Helps,

James Brundage [MSFT]

Author

PowerShell Team
PowerShell Team

PowerShell is a task-based command-line shell and scripting language built on .NET. PowerShell helps system administrators and power-users rapidly automate tasks that manage operating systems (Linux, macOS, and Windows) and processes.

0 comments

Discussion are closed.