Skip to content

Instantly share code, notes, and snippets.

@altrive
Created December 18, 2013 14:16
Show Gist options
  • Select an option

  • Save altrive/8023060 to your computer and use it in GitHub Desktop.

Select an option

Save altrive/8023060 to your computer and use it in GitHub Desktop.
Add-Type wrapper cmdlet. UseTypeAlias=$true to avoid type name conflict.when Add-Type called multiple times. See also https://gist.github.com/altrive/6765957
function Add-TypeDefinition
{
[CmdletBinding()]
param (
[string] $Path,
[string[]] $ReferencedAssemblies = @("Microsoft.CSharp"),
[string] $OutputAssembly,
[switch] $IgnoreWarnings,
[switch] $UseTypeAlias
)
$ErrorActionPreference = "Stop"
if (!(Test-Path $Path)){
Write-Error ("Specified path '{0}' is not exists" -f $Path)
}
if ($Path.EndsWith(".cs"))
{
$files = New-Object IO.FileInfo($Path)
}
else
{
$files = Get-ChildItem -Path $Path -Filter "*.cs" -Recurse -File
}
if (($files -eq $null) -or $files.Count -eq 0){
return
}
#Merge C# code files to import definitions
$sb = New-Object Text.StringBuilder
foreach ($file in $files)
{
#Write-Verbose ("Add C# type definition from file '{0}'" -f $file.Name)
$content = Get-Content $file.FullName -Raw
$sb.AppendLine($content) > $null
}
$params = @{
ReferencedAssemblies = $ReferencedAssemblies
IgnoreWarnings = $IgnoreWarnings
}
if (![String]::IsNullOrEmpty($OutputAssembly)){
$params.Add("OutputAssembly", $OutputAssembly)
}
if ($UseTypeAlias)
{
#Guid suffix to create unique class name
$uniqueSuffix = "_{0}" -f [Guid]::NewGuid().ToString().Replace("-", "_")
#Regex to find class declarations
$regex = [regex] "(?<=public\s+(static\s+)?(partial\s+)?class\s+)\w+"
#Replace class name to unique name
$code = $regex.Replace($sb.ToString(), [String]::Format("{0}{1}", "$&", $uniqueSuffix))
#Add replaced code definition
Add-Type @params -TypeDefinition $code
#Add Alias to original class name
foreach ($match in $regex.Matches($code))
{
$className = $match.Value.Replace($uniqueSuffix, "")
#Write-Verbose ("Set class name alias '{0}' to '{1}'" -f $className, $match.Value) -Verbose
[PSObject].Assembly.GetType("System.Management.Automation.TypeAccelerators")::Add($className, $match.Value)
}
}
else
{
#Add replaced code definition
Write-Verbose "Call Add-Type with no type aliases"
Add-Type @params -TypeDefinition $sb.ToString()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment