Skip to content

Instantly share code, notes, and snippets.

@fsackur
Created April 1, 2018 20:24
Show Gist options
  • Save fsackur/1d17bbfbe911f9f390ab4c5f4a948607 to your computer and use it in GitHub Desktop.
Save fsackur/1d17bbfbe911f9f390ab4c5f4a948607 to your computer and use it in GitHub Desktop.
<#
When you are roughing out a C# type in powershell, and you don't want to fire up
Visual Studio, it can get tiresome having to constantly reload your script editor.
This increments the class name each time you compile it.
Blogged in https://fsackur.github.io/2018/03/30/Reflecting-on-types/
#>
$TypeDef = @'
using System;
using System.Management.Automation;
using System.Collections;
using System.Collections.Generic;
public class TestClass
{
private string Thing;
public string GetThing()
{
return Thing;
}
}
'@
if (-not $i) {$Global:i = 1} else {$i++}
if ($TypeDef -match 'class\s+(\w+)\b')
{
$ClassName = $Matches.1
}
else
{
throw "Couldn't parse class name from source code"
}
$TypeDef = $TypeDef -replace ([Regex]::Escape($ClassName) + '\b'), "$ClassName$i"
$ClassName += $i
$TypesToReference = @(
#Add any types here from non-default assemblies
#[System.Web.Script.Serialization.JavaScriptSerializer]
)
$AssembliesToReference = $TypesToReference.Assembly
$Types = Add-Type -TypeDefinition $TypeDef -PassThru -ErrorAction Continue -ReferencedAssemblies $AssembliesToReference
$Type = $Types | ? Name -eq $ClassName
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment