How to run .cs file with powershell

Posted by & filed under .

It is so easy.

First, lets put our c# code into a powershell string.
Here is the example.

$exampleCode=@'using System;
using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Windows.Media.Imaging;
using System.Xml;

public partial class Form1 : Form

   public Form1()

If you are using WPF classes, you should use Powershell in STA mode. We can add a control of this situation.

If ($host.Runspace.ApartmentState -ne 'STA')
    Write-Warning "You are not in a sta-mode"

Then here is the assemblies that we will use.

$UsingAssemblies= ('System.Windows.Forms','System.Drawing','PresentationCore','WindowsBase','System.Xml')

    Add-Type -TypeDefinition $exampleCode -ReferencedAssemblies $UsingAssemblies -ErrorAction STOP
    (New-Object Form1).ShowDialog() | Out-Null
        Write-Warning "Error :  $($Error[0].Exception.Message)"

That’s how we can call cs file in a powershell.