Currently my C++ application launching/executing powershell scripts using createprocess method(can be achieved using system or shellexecute). This takes a while because it launches a commandline and then executing the script. Is there any windows API available to call powershell scripts from C++?
-
1[Windows PowerShell Host Quickstart](https://learn.microsoft.com/en-us/powershell/scripting/developer/hosting/windows-powershell-host-quickstart) is listed under the *Legacy PowerShell SDK* documentation section. Sounds like that allows you to execute scripts in your own hosting environment. I don't know whether that is still supported, or whether it provides interfaces for consuming it from a native application. – IInspectable Aug 30 '20 at 20:12
-
I don't think you can achieve it through pure C++ and windows API, you can refer to [Would like to run PowerShell code from inside a C++ program](https://stackoverflow.com/questions/56499270/would-like-to-run-powershell-code-from-inside-a-c-program) and [C++ and Powershell](https://stackoverflow.com/questions/19634220/c-and-powershell) – Zeus Aug 31 '20 at 03:25
1 Answers
The PowerShell executables (powershell.exe, powershell_ise.exe, pwsh.exe) are just hosts themselves... and yes you can create your own.
'create your own PowerShell host'
PowerShell Runspaces When you execute PowerShell commands it is actually the runspace that is doing the execution work and handling the execution pipeline. The host is mostly responsible for handling input and output streams to interact with the runspace. Examples of hosts are PowerShell.exe, PowerShell ISE or a custom console, WPF, WinForms or Windows service application. The different hosts interact with the PowerShell runspace behind the scenes. When you create your own host you are creating a runspace instance and passing it commands to execute.
Creating A Runspace Creating the default runspace is pretty easy, just call:
PowerShell ps = PowerShell.Create();
Note: You will need a reference to System.Management.Automation for the code to work.
Video: Hosting PowerShell In WPF
So, this really a duplicate of this SO Q&A

- 15,138
- 2
- 14
- 25
-
2The question is explicitly asking for doing this with C++. You have posted C# code (presumably) and provided instructions for doing this from a .NET application. – IInspectable Aug 31 '20 at 08:55