DataOgre
Blog
Let's say, hypothetically of course, that the PowerShell syntax just doesn't feel that natural to you. If you are more comfortable writing .NET...

Powershell Training Wheels

November 13, 2012

Let's say, hypothetically of course, that the PowerShell syntax just doesn't feel that natural to you. If you are more comfortable writing .NET code, but need to run it as a PowerShell script, this post is going to put a smile on your face. I recently wrote a complex script, and knew that I could write and test it much more quickly in C#, and thought I could easily port it to PowerShell afterwards. The C# version was more complicated and took longer than expected. Plus, the deadline was looming, so I quickly searched for something that would convert C# to PowerShell. The good news was that it looked like there was at least one free .NET Reflector Add-In that would do exactly that. The bad news is that .NET Reflector itself is no longer free. That's when I found something that I liked just as well, if not better.

Add-Type PowerShell cmdlet

Now, depending on what you are trying to with Add-Type, there can be some challenges (see [Powershell Add-Type - Where's That Assembly!](http://sqldbamusings.blogspot.com/2012/06/powershell-add-type-wheres-that.html) for more information). However, for much of what you might be doing with .NET, it works perfectly. Here is an example that logs the number of files found in each of your My Music folders that should give you a taste of what you can do with Add-Type:

$cSharp = @"
  using System;
  using System.IO;
  using System.Text;
  public class Library {
    public void Catalog() {
      string musicFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
      string logFile = string.Format("{0}{1}", Path.GetTempPath(), "Catalog.csv");
      StringBuilder output = new StringBuilder();
      output.AppendLine("Directory|FileCount");

      using (StreamWriter sw = new StreamWriter(logFile, false)) {
        LogFileCount(output, musicFolder);
        sw.Write(output.ToString());
      }
    }
    private void LogFileCount(StringBuilder output, string folder) {
      int fileCount = 0;
      DirectoryInfo di = new DirectoryInfo(folder);
      foreach(FileInfo fi in di.GetFiles("*.*")) {
        fileCount++;
      }

      output.AppendLine(di.FullName + "|" + fileCount.ToString());
      foreach(DirectoryInfo sdi in di.GetDirectories()) {
        LogFileCount(output, sdi.FullName);
      }
    }
  }
"@

Add-Type -TypeDefinition $cSharp
#This is an example of how you would reference other .NET assemblies if needed
#Add-Type -TypeDefinition $cSharp -reference System.Data, System.Globalization
$LibraryObject = New-Object Library
$LibraryObject.Catalog();