How to Run C# Code in PowerShell

This article shows how to run C# Code in PowerShell by adding Inline C# or C# source code file to PowerShell.

Use Add-Type Cmdlet

The Add-Type cmdlet Microsoft defined is to run .NET Class in PowerShell Session. This will be used to add C# inline or read the C# code file.

Method 1 : Add-Type -TypeDefinition $code -Language CSharp

This is a C# code inline example in case only default assemblies are referenced.

Set-Location $PSScriptRoot
$checkDirectory = 'D:\Tests'

$cs_source = @"
using System;
using System.IO;

namespace TechAdviz
{
  public static class SampleBase
  {
   
      public static void listfiles(string basedirectory)
      {
           string[] fs = Directory.GetFiles(basedirectory,"*.*", SearchOption.AllDirectories);

            foreach (string f in fs)
            {
               Console.WriteLine(f);
            }
        }
     }
}
"@


Add-Type -TypeDefinition $cs_source -Language CSharp

[TechAdviz.SampleBase]::listfiles($checkDirectory)

Method 2 : Add-Type -ReferencedAssemblies $assemblies -TypeDefinition $code -Language CSharp

ReferenceAssemblies is a parameter to add more referenced assemblies in addition to default ones with the Add-Type cmdlet.

$extractDirectory = 'D:\Ext'
$zipfile = 'D:\Simple.zip'

$cs_source = @"
using System.IO;
using System.IO.Compression;

namespace TechAdviz
{
  public static class SampleBase2
  {
   
      public static void extractZipToDir(string zipPath, string targetdirectory)
      { 
            ZipFile.ExtractToDirectory(zipPath, targetdirectory);         
        }
     }
}
"@


$assemblies=(
 "System.IO.Compression" )

Add-Type -ReferencedAssemblies $assemblies -TypeDefinition $cs_source -Language CSharp

[TechAdviz.SampleBase2]::extractZipToDir($zipfile, $extractDirectory)

Method 3: Read C# file and Run with Add-Type

-Path parameter specifies the path to the C# source code file, and the Add-Type cmdlet uses the source file extension to define Type of Compiler.

$csFile = 'D:\Tests\Sample.cs'

$assemblies=(
 "System.IO.Compression","System.IO.Compression.FileSystem"
)

Add-Type -Path $csFile -ReferencedAssemblies $assemblies

$zipfile ='D:\Simple.zip'
$extractDirectory='D:\ext'
[TechAdviz.SampleBase3]::extractZipToDir3($zipfile, $extractDirectory)

You may also want to check:

How to Create C# Inline Task in MSBuild

Useful List of PowerShell Commands

Leave a Comment