2

I know it is possible to call C# code from the PowerShell script by loading an assembly. But is there any way to pass and receive a value in between both C# code and PowerShell script.

Let's say I have a $path variable in my power script. I want to pass it to my c# code. And C# code will use the $path. After doing some stuff in the c# code it will return some value to the script. Is this possible? If it is, how can I do it? I must load a third party dll in my power shell and all one or two public methods on that dll to complete some task.

My PowerShell script code:

    $scriptpath = $MyInvocation.MyCommand.Path;
    $cureentDir = Split-Path $scriptpath;
    $isSasDir = $cureentDir -match "mydir";
    $requiredFile = "Core.dll";
    $myPowersehllVal = "has value for c# code"; 

My C# code:

$Source = @"
    using System.Net;

    public class ExtendedWebClient : WebClient
    {
        String myPowersehllVal;
        public int Timeout;
        protected override WebRequest GetWebRequest(System.Uri address)
        {

        }
     }
"@;
u8it
  • 3,956
  • 1
  • 20
  • 33
masiboo
  • 4,537
  • 9
  • 75
  • 136

1 Answers1

0

For getting PS values into C#

https://stackoverflow.com/a/22384009/3546415


In a more general sense, System.Management.Automation (Nuget Required) looks promising, in particular, Runspace and Pipeline.

Here are some good examples of usage: https://msdn.microsoft.com/en-us/library/ee706576(v=vs.85).aspx

Something like this one seems similar to what you want.

Or maybe just use the PowerShell Class to execute PS commands from your C# module to set PS variable values.


Alternatively, without worrying about interop, you can kind of hack this by working through the file system and/or environmental variables. Following this paradigm, you could even use a memory mapped file and share variables with a broader set of applications. Powershell side would be something like this. For objects, serialization.

u8it
  • 3,956
  • 1
  • 20
  • 33