1

I am currently opening a Runspace and running a Powershell process from C# using System.Management.Automation, and feeding it PS scripts. I'd like to insert a C# Serilog logger object into the Powershell process so that I can create logs from within the scripts.
I've been able to add the object as a runspace variable and see the object in the Powershell process, however, none of the members or methods are available. When I look at the available members that the logger object has within Powershell, it appears to be just an Object (contains only ToString(), GetType(), etc).

Any idea why I can't see the methods? PS - I do NOT want to write the C# class within the script.

Here's my code. runspace.SessionStateProxy.SetVariable("logger", _logger); adds the _logger to the Powershell process:

using var instance = new PowerShellProcessInstance(new Version(5, 1), null, null, false);
        using var runspace = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(Array.Empty<string>()), instance);
        runspace.Open();
        runspace.SessionStateProxy.SetVariable("logger", _logger);

        PowerShell? powerShell = null;
        using var powershellDisposer = new ActionDisposable(() =>
        {
            powerShell?.Dispose();
        });
        try
        {
            powerShell = PowerShell.Create(runspace);
        }
        catch (Exception ex)
        {
            _logger.Error($"Failure to create a new PowerShell runspace to run script: {scriptName}: {ex.Message}");
            throw;
        }

Here's my script:

param($logger)
$logger.Information("Log here!")

Here is an example of someone wanting to do the same thing. I've tried to follow these answers and that brought me to where I am now. This post is 10 years old.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.