首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >$global:在PowerShell会话中设置,但在System.Management.Automation.PowerShell实例中没有设置

$global:在PowerShell会话中设置,但在System.Management.Automation.PowerShell实例中没有设置
EN

Stack Overflow用户
提问于 2017-08-15 17:02:02
回答 1查看 204关注 0票数 1

我正在将通常在独立的PowerShell会话中运行的PowerShell脚本(StartBackup.ps1)的执行转移到C#应用程序中。脚本通常在PowerShell中直接执行,导入模块/DLL,调用其他脚本并设置大量变量。

在C#应用程序中,我有:

代码语言:javascript
复制
using (PowerShell powerShell = PowerShell.Create())
{
    powerShell.AddCommand("Set-ExecutionPolicy");
    powerShell.AddParameter("Scope", "Process");
    powerShell.AddParameter("ExecutionPolicy", "RemoteSigned");

    powerShell.AddCommand("Set-Location");
    powerShell.AddParameter("Path", "E:\\BackupTools");

    powerShell.AddCommand("E:\\BackupTools\\StartBackup.ps1", false);
    powerShell.AddParameter("Type", "Closed");

    Collection<PSObject> results = powerShell.Invoke();

    foreach (var resultItem in results)
    {
        ...
    }
}

上面的代码运行得很好,直到设置了$global:,然后才开始抛出错误。所有这些值都为空/空。

我添加了几个powerShell.AddCommands来检查脚本执行后是否设置了这些值,并且它们在PowerShell实例中都是空的。在独立的外壳里,它们都设置得很好。

这里有什么问题?为什么PowerShell实例与实际的shell不同?

编辑:其目的不是仅仅是点燃和-忘记脚本。这样做的目的是让它完成它的工作,然后继续处理它在PowerShell实例中留下的任何工件,就像我通常在powershell.exe中一样。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-08-15 17:46:22

如果您只想执行现有的PowerShell脚本,最简单的方法就是使用流程类。您可以构建命令行并运行它。

如果要在C#代码中构建脚本本身,则需要使用PowerShell类。

而且,您的AddCommand将链接这些命令。这是你的要求吗?

MSDN员额

调用AddCommand()方法将此内容添加到执行管道

代码语言:javascript
复制
using (PowerShell PowerShellInstance = PowerShell.Create())
{
    // use "AddScript" to add the contents of a script file to the end of the execution pipeline.
    // use "AddCommand" to add individual commands/cmdlets to the end of the execution pipeline.
    PowerShellInstance.AddScript("param($param1) $d = get-date; $s = 'test string value'; " +
            "$d; $s; $param1; get-service");

    // use "AddParameter" to add a single parameter to the last command/script on the pipeline.
    PowerShellInstance.AddParameter("param1", "parameter 1 value!");
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45697800

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档