0

I am trying to call a PowerShell code from C# but environment variables are not getting "inherited" and when I try to manually set the environment variables its empty.

// The difference between CreateDefault and CreateDefault2 is that
// CreateDefault includes engine snap-ins, while CreateDefault2 does not.
var initialState = InitialSessionState.CreateDefault2();
initialState.EnvironmentVariables.Add(Environment.GetEnvironmentVariables()
    .Cast<DictionaryEntry>()
    .Select(x => new SessionStateVariableEntry(x.Key.ToString(), x.Value,
        $"Setting environment variable {x.Key} to {x.Value}")));

using var ps = PowerShell.Create(initialState);
var results = await ps.AddScript("dir env:").InvokeAsync();
foreach (var result in results)
{
    Debug.Write(result.ToString());
}

This is what I get in results

Enumeration yielded no results

1 Answer 1

1

Give the following a try:

public static async Task<string> Execute()
{
    StringBuilder sb = new StringBuilder();

    // The difference between CreateDefault and CreateDefault2 is that
    // CreateDefault includes engine snap-ins, while CreateDefault2 does not.
    var initialState = InitialSessionState.CreateDefault2();
    initialState.EnvironmentVariables.Add(Environment.GetEnvironmentVariables()
        .Cast<DictionaryEntry>()
        .Select(x => new SessionStateVariableEntry(x.Key.ToString(), x.Value,
            $"Setting environment variable {x.Key} to {x.Value}")));

    using var ps = PowerShell.Create(initialState);
    var results = await ps.AddScript("dir env:").InvokeAsync();
    //var results = await ps.AddCommand("Get-ChildItem").AddParameter("Path", "Env:").InvokeAsync();

    foreach (PSObject outputItem in results)
    {
        DictionaryEntry entry = (DictionaryEntry)outputItem.BaseObject;
        Debug.WriteLine($"EnvVar Key: '{entry.Key}' Value: '{entry.Value}'");
        sb.AppendLine($"{entry.Key}: {entry.Value}");
    }

    return sb.ToString();
}

Resources:

Sign up to request clarification or add additional context in comments.

Comments

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.