简体   繁体   中英

C# calling PowerShell and passing environment variables

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

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 :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM