想从 C++ 程序中运行 PowerShell 代码

Bul*_*aur 0 c++ powershell

我希望能够从我的 C++ 程序中运行 30 行 PowerShell 脚本。我听说这是一个糟糕的主意,我不在乎。我还是想知道怎么做。

我只想直接在 C++ 程序中编码,我不想从外部调用 PowerShell 脚本。有没有办法做到这一点?如果不可能,就说不。

例如

void runPScode() {

//command to tell compiler the following is PowerShell code
//a bunch of PowerShell code

}
Run Code Online (Sandbox Code Playgroud)

谢谢!

我一直在寻找执行此操作的命令并阅读了几个“类似”的问题。

Sev*_*yev 9

这只是为了完整起见:


PowerShell 有一个 API - 请参阅System.Management.Automation.PowerShell。API 是管理的(即基于 .NET)。可以构建混合模式 C++ 应用程序并从托管部分调用所述 API。

将以下内容放入单独的 C++ 文件中:

#include "stdafx.h"
#include <vcclr.h>
#using <mscorlib.dll>
#using <System.dll>
#using <System.Management.Automation.dll>

using namespace System;
using namespace System::Management::Automation;

void RunPowerShell(LPCWSTR s)
{
    PowerShell::Create()->AddScript(gcnew String(s))->Invoke();
}
Run Code Online (Sandbox Code Playgroud)

在项目属性中,在 VC++ 目录下,添加C:\Program Files (x86)\Reference Assemblies\Microsoft\WindowsPowerShell\3.0到参考目录(您的路径可能会有所不同)。

仅为该文件设置以下编译器选项:

  • 公共语言运行时支持 (/clr)
  • 调试信息格式 - 程序数据库 (/Zi)
  • 启用 C++ 异常 - 否
  • 基本运行时检查 - 默认
  • 预编译头 - 不使用预编译头

您需要/clr从 C++ 调用 .NET,但/clr与许多其他 C++ 选项不兼容。如果你错过了什么,编译器错误消息会让你知道。

void RunPowerShell(LPCWSTR)在项目的非托管部分声明为常规外部函数,根据需要调用。


也就是说,无论您的 Powershell 做什么,C++/Win32 都可能也能做到

  • 在我的 Visual Studio 2019 中,我也必须使用“一致性模式:否(/许可)”。 (2认同)