PoshCode Archive  Artifact [723e00a238]

Artifact 723e00a238f50eda02a1690dc079da7b45e5da38972af077583fa279db9746a6:

  • File POC-csharp-expressions.ps1 — part of check-in [f3838b7f46] at 2018-06-10 12:59:06 on branch trunk — proof of concept of running csharp expressions in powershell v2. very basic, no error checking. (user: oisin size: 1765)

# encoding: ascii
# api: csharp
# title: POC csharp expressions
# description: proof of concept of running csharp expressions in powershell v2. very basic, no error checking. 
# version: 0.1
# type: function
# author: oisin
# license: CC0
# function: run-csharpexpression
# x-poshcode-id: 1609
# x-archived: 2010-02-03T16:08:51
#
# -karl prosser
# add dynamic namespace (refactored)
# -Oisin
# -changed it to compile to a temporary dll so that C# expressions that returned anonymous types could run more than once without having an exception.
#
$mytypes = @()
function run-csharpexpression([string] $expression )
{
$global:ccounter = [int]$ccounter + 1
$local:name  =  [system.guid]::NewGuid().tostring().replace('-','_').insert(0,"csharpexpr")
$local:ns = "ShellTools.DynamicCSharpExpression.N${ccounter}"

$local:template = @"
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;

namespace $ns
{
public static class Runner
{
public static object RunExpression()
{
return [[EXPRESSION]];
}
}
}
"@

$local:source = $local:template.replace("[[EXPRESSION]]",$expression)
#saving to a temporary file so that the error with anonymous types with the same signature doesn't happen
$local:filename = [System.IO.Path]::GetTempFileName()
$null = add-Type $local:source -Language CsharpVersion3 -outputassembly $local:filename 
$null = [System.Reflection.Assembly]::LoadFile($local:filename )
invoke-Expression ('[' + $local:ns + '.Runner]::RunExpression()')
}

set-alias c run-csharpexpression

#test code
c "new{a=1,b=2,c=3}"
c "new{a=1,b=2,c=3}"
(c DateTime.Now).adddays(5)
(c "new{a=1,b=2,c=3}").b
c 'from x in Directory.GetFiles(@"c:\downloads") where x.Contains("win") select x'