Passing a custom object from C # to Powershell

I have a C # class that a Powershell script should execute, passing it a log object. The journal is fully written in C # and should be used in conjunction with C # and Powershell code to achieve general logging.

Can someone please tell me how can I pass a custom object from C # to Powershell and use it there?

+5
source share
4 answers

I believe using runpace will solve your problem. You can find a good explanation and examples on them at the following link: http://www.codeproject.com/Articles/18229/How-to-run-PowerShell-scripts-from-C .

, .

script:

param($logger2)
$logger2.Write("logger2 Write was called");
$logger.Write("logger Write was called");

logger2 logger :

String scriptContent = // get script content
Logger logger = new Logger();
Logger2 logger2 = new Logger2();
// create ps runspace
using (Runspace runspace = RunspaceFactory.CreateRunspace())
{
    // start session
    runspace.Open();
    // set variables
    runspace.SessionStateProxy.SetVariable("logger", logger);
    // supply commands
    using (Pipeline pipeline = runspace.CreatePipeline())
    {
        // create ps representation of the script
        Command script = new Command(scriptContent, true, false);
        // suppy parameters to the script
        script.Parameters.Add(new CommandParameter("logger2", logger2));
        // send script to pipeline
        pipeline.Commands.Add(script);
        // execute it
        Collection<PSObject> results = pipeline.Invoke();
        // close runspace
        runspace.Close();
    }
}
+2

PowerShell #, Log LoadFile PowerShell ( V1 V2)

$lib = [System.Reflection.Assembly]::LoadFile('path to your dll');
$lib.Log("Terrible things have happened!")

PowerShell #, SessionStateProxy.SetVariable.

+1

PowerShell script, C# script .

.

Add-Type -TypeDefinition <C# code> -Language CSharp

+1

system.management.automation.dll PowerShell. . , ,

ps.AddCommand("Get-Process");

- :

ps.AddCommand(<script-path/name-of-script-in-path>).AddParameter("Log", logInstance);

It tells you to call your script with a parameter Logwhose value is the instance logInstanceto be passed to the script. The script should have a parameter Logand use it as $Login its code:

param($Log)

$Log.Write("Begin ...")
...
$Log.Write("End ...")
0
source

All Articles