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.
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");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.