How can I Use Add-Type to add C# code with System.Windows.Forms namespace?

4.4k Views Asked by At

How can I use Add-Type to add C# code with System.Windows.Forms namespace? I tried this command:

Add-Type -TypeDefinition @"
using System;
using System.Windows.Forms;

namespace testnamespace
{
    public static class testclass
    {
        public static string messagebox()
        {
            MessageBox.Show("test")
            return "test";
        }
    }
}
"@ 

but I'm getting some error like:

The type or namespace name 'Forms' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?)

I just want to use ONLY C# code in PowerShell. Please don't give me alternative.

1

There are 1 best solutions below

0
Mathias R. Jessen On BEST ANSWER

Add a reference to the containing assembly (the System.Windows.Forms.dll file), using the ReferencedAssemblies parameter:

Add-Type -TypeDefinition @"
using System;
using System.Windows.Forms;

namespace TestNamespace
{
    public static class TestClass
    {
        public static string MessageBox()
        {
            MessageBox.Show("test");
            return "test";
        }
    }
}
"@ -ReferencedAssemblies System.Windows.Forms