Call to powershell process from inlined C#

108 views Asked by At

I have a PowerShell script that execute some inlined C# code like this:

Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp
[AnalyzeHelper.AnalyzeDirectories]::CheckPath("XXX")

In that C# code I would like to output to my PowerShell output. So in my C# I have implemented:

public static void CheckPath(string path)
{
    WriteOutput("Begin CheckPath");
}

private static void WriteOutput(string text)
{
  using (PowerShell powerShellInstance = PowerShell.Create())
  {
    powerShellInstance.AddCommand("Write-Host").AddParameter("string", text).Invoke();
  }
}

But unfortunately it doesn't work. It actually just hang in the invoke call.

1

There are 1 answers

2
JerryA On

It turns out that PowerShell supports delegates so solution was quite simple. I called like this:

[Action[string]]$action = {param($message) Write-Host "$message"}
Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp
[AnalyzeStringLibraries.AnalyzeStrings]::CheckPath("XXX", $action)

Then in the C# I can do like this:

public static void CheckPath(string path, Action<string> writeToHost)
{
    writeToHost("Begin CheckPath");
}