Home > front end >  C# calling PowerShell and passing environment variables
C# calling PowerShell and passing environment variables

Time:10-07

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

CodePudding user response:

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:

  • Related