[英]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.我正在尝试从 C# 调用 PowerShell 代码,但环境变量没有得到“继承”,当我尝试手动将环境变量设置为空时。
// 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
这是我得到的
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 :资源:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.