【问题标题】:How to have the $Env variable available in the script?如何在脚本中使用 $Env 变量?
【发布时间】:2020-05-26 23:41:32
【问题描述】:

我正在使用 C# 执行 powershell 脚本,但是当我尝试在 powershell 脚本中获取环境变量时它不起作用。

如果我使用控制台手动运行 powershell 脚本,它可以工作。

您对如何解决此问题有任何想法吗?

C# 代码示例:

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();

// set directory for ps
if (!string.IsNullOrEmpty(sessionPath))
    runspace.SessionStateProxy.Path.SetLocation(sessionPath);

Pipeline pipeline = runspace.CreatePipeline();
Command command = new Command(script, false);
pipeline.Commands.Add(command);
pipeline.Commands.Add("Out-String");
pipeline.InvokeAsync();

脚本powershell:

$path = $env:PATH;
write-output $path # this is empty ! $env does seems to exist in the runspace ? 

【问题讨论】:

  • 我通过使用脚本 here 找到了一种解决方法,但我更愿意找到如何配置运行空间以便设置 Env 变量。

标签: c# powershell


【解决方案1】:

改变这一行:

Command command = new Command(script, false);

Command command = new Command(script, true);

您的script 变量是一个脚本(多个命令)。通过传递 false,PowerShell 认为 script 命名了一个命令。

【讨论】:

  • 我将 .ps1 文件路径作为命令传递,如果我使用 (script,true) 它不起作用。
  • 为了让它工作,我首先将文件作为字符串读取,然后我使用 Command command = new Command(script, true);
【解决方案2】:

也许您可以在您的 PowerShell 脚本中尝试使用此代码。无论如何调用脚本,这都应该有效:

$path = [environment]::GetEnvironmentVariable("Path")
write-output $path

更多关于这种环境变量操作的信息可以在here找到。

【讨论】:

    【解决方案3】:

    唯一想到的是,您在创建运行空间时没有传入配置。

    var config = RunspaceConfiguration.Create();
    var runspace = RunspaceFactory.CreateRunspace(config);
    

    我在托管 Powershell 时所做的唯一一件事就是为 Powershell 插件编写单元测试。代码在这里:https://github.com/openxtra/TimeTag/tree/master/Test

    查看测试项目的 DatabasePoSHSnapInTest 和 PowerStatsPoSHSnapInTest 文件夹。

    【讨论】:

    • 当我创建一个新配置并将它传递给我的运行空间时也没有工作。
    猜你喜欢
    • 2021-12-24
    • 2016-02-29
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2023-04-03
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多