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