【问题标题】:Access Powershell via Visual C++ (API)通过 Visual C++ (API) 访问 Powershell
【发布时间】:2011-01-06 03:14:51
【问题描述】:

我想编写一个有效地“管道”Powershell 的程序,这样我就可以在 C++ 中发送命令并解析响应,而无需实际打开屏幕上的提示。

有什么建议吗?

【问题讨论】:

    标签: c++ windows powershell


    【解决方案1】:

    您当然可以这样做,但您需要使用托管代码,因为 PowerShell 的架构完全基于 CLR 对象模型。

    我不确定 C++ 语法,但您可以从 System.Management.Automation.dll 中的 PowerShell 类开始,并使用其静态 Create 方法创建一个实例,您可以将数据传输到该实例并运行命令。

    【讨论】:

    • 请注意,您也可以专门为此创建一个托管 DLL,并使用 the solutions here 之一从非托管 C++ 调用它。
    【解决方案2】:

    我有一个答案可能会解决您的问题,尽管它并不是您所提问题的真正答案。

    嗯,我目前的项目需要的是一个不打开窗口的系统调用,它确实让我有机会读出写入标准输出或标准错误的结果。

    如果您可以接受 - 这是前面提到的代码库中的一些代码:

    public class RsbSystem
    {
        string command = null;
        string param = null;
        string commandLine = null;
        public int ExitCode = 0;
    
        //..
    
        /// <summary>Exec for apps that don't want console output</summary>
        /// <param name="msg">returns output of called program</param>
        /// <returns>0 if ok</returns>
        /// <remarks>RsbSystem instance keeps the result in member ExitCode</remarks>
        public int Exec(ref string msg)
        {
            var p = new Process();
            p.StartInfo.FileName = command;
            p.StartInfo.Arguments = param;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.Start();
            if (!p.StandardOutput.EndOfStream)
                msg = p.StandardOutput.ReadToEnd();
            if (!p.StandardError.EndOfStream)
                msg += p.StandardError.ReadToEnd();
            p.WaitForExit(120000);  // this needs to come after readToEnd() RSB: https://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput(v=vs.110).aspx
            ExitCode = p.ExitCode;
            p.Dispose();
            return ExitCode;
        }
    
        // ..
    
        public RsbSystem(string cmdLine)
        {
            commandLine = cmdLine;
            var pos = 0;
            if (cmdLine[0] == '"')
                pos = cmdLine.IndexOf("\" ") + 1;
            else pos = cmdLine.IndexOf(" ");
            command = pos > -1 ? cmdLine.Substring(0, pos).Trim() : cmdLine;
            param = pos > -1 ? cmdLine.Substring(pos + 1).TrimStart() : "";
        }
    }
    

    另外:请原谅我的代码是 C# 而不是 C++。

    如您所见,它调用任何程序 - 并且不使用 PowerShell。如果这已经是您的解决方法 - 很好。如果没有,您可以考虑使用this approach 从命令行调用 Powershell,并可能以这种方式到达您想要的位置。

    希望它对您有所帮助或至少给您一个想法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-10
      • 1970-01-01
      • 2016-01-08
      • 2012-04-09
      • 2023-01-04
      • 2021-03-19
      相关资源
      最近更新 更多