🎯 Steps to Execute PowerShell from C++ via C++/CLI DLL (Visual Studio 2022 / C++)
✅ Overall Structure
🔹 ① CLI Wrapper DLL (C++/CLI)
Provides functionality to execute PowerShell scripts.
🔹 ② C++ caller with /clr enabled
Calls the CLI DLL to execute PowerShell scripts.
🔧 Step 1: Create CLI Wrapper DLL Project
1. Create Project
- [Create a new project] → [C++] → CLR Class Library (.NET Framework)
- Name:
PowerShellWrapper
💡 If this template is not displayed, install the “.NET desktop development” workload.
2. Add NuGet Package
- Right-click the project → [Manage NuGet Packages]
- Add the
Microsoft.PowerShell.5.ReferenceAssembliesNuGet package, version 1.1.0. It provides reference assemblies for Windows PowerShell 5.1.
3. Implement CLI Side Code
PowerShellWrapper.h
| |
PowerShellWrapper.cpp
| |
🔧 Step 2: Create the caller with /clr enabled
1. Create C++ Console App Project
- Name:
NativeApp
2. Add Reference
- Right-click the project → [Add] → [Reference] → [Projects] → Add
PowerShellWrapper - [Configuration Properties] → [C/C++] → [Common Language Runtime Support] → Change to /clr
3. Execution Code (main.cpp)
| |
💡 Note (IDL / TLB / COM Registration)
- Since this configuration references the .NET DLL directly instead of using COM, IDL, TLB, and COM registration are not required.
✅ Final Structure
| |
⚠️ Runtime and security notes
The target Windows machine must provide Windows PowerShell 5.1 and a compatible .NET Framework.
This example targets Windows PowerShell 5.1 and .NET Framework 4.7.2 or later. Install “C++/CLI support for v143 build tools” in Visual Studio Installer and select the matching target framework.
This example does not run PowerShell 7. For PowerShell 7, design a separate host targeting the same .NET runtime, or launch pwsh as a child process. C++/CLI projects targeting modern .NET build as DLLs.
AddScript executes its string as code. Never concatenate untrusted input. For user-supplied values, prefer fixed commands with parameters and consider a constrained runspace. Scripts run with the application’s user permissions. This sample uses the default runspace.
Build both projects for the same .NET Framework target, configuration (Debug/Release), and platform architecture (x86/x64). Enabling /clr makes the caller a mixed-mode executable, not a native-only executable.
![Featured image of post [VS2022] Execute PowerShell from C++! Integration Steps via C++/CLI DLL](/p/c-%E3%81%8B%E3%82%89-powershell-%E3%82%92-c-cli-dll-%E7%B5%8C%E7%94%B1%E3%81%A7%E5%AE%9F%E8%A1%8C%E3%81%99%E3%82%8B%E6%89%8B%E9%A0%86/img_hu9521166642857669203.webp)