我正在将通常在独立的PowerShell会话中运行的PowerShell脚本(StartBackup.ps1)的执行转移到C#应用程序中。脚本通常在PowerShell中直接执行,导入模块/DLL,调用其他脚本并设置大量变量。
在C#应用程序中,我有:
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中一样。
发布于 2017-08-15 17:46:22
如果您只想执行现有的PowerShell脚本,最简单的方法就是使用流程类。您可以构建命令行并运行它。
如果要在C#代码中构建脚本本身,则需要使用PowerShell类。
而且,您的AddCommand将链接这些命令。这是你的要求吗?
调用AddCommand()方法将此内容添加到执行管道。
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!");
}https://stackoverflow.com/questions/45697800
复制相似问题