Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should C++ execute the PowerShell command?

Tags:

c++

powershell

I want to execute the PowerShell command in C + + programming. I've edited the command statement that needs to be run.PowerShell_CMD、XML_File

like image 340
kevin Avatar asked Oct 16 '25 19:10

kevin


1 Answers

My assumption here is that you're trying to add -auto to the arguments. After reviewing the supplied image I would change the PowerShell code as well.

$task = Get-ScheduledTask "Test"
$items = @{}
if ($task.Actions.Execute -ne $null) {$items.Add('Execute', "$($task.Actions.Execute)")} 
$items.Add('Argument', "$($task.Actions.Arguments) -auto") 
if ($task.Actions.WorkingDirectory -ne $null) {$items.Add('WorkingDirectory',"$($task.Actions.WorkingDirectory)")} 
$action = New-ScheduledTaskAction @items
$task.Actions = $action
Set-ScheduledTask -InputObject $task


Far simpler and easier to understand.

To run this in c++ you should dump the code to a temporary file.

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream file;
    file.open("test.ps1");

    string newArg = "-auto";
    string powershell;
    powershell = "$task = Get-ScheduledTask \"Test\"\n";
    powershell += "$items = @{}\n";
    powershell += "if ($task.Actions.Execute -ne $null) {$items.Add('Execute', \"$($task.Actions.Execute)\")} \n";
    powershell += "$items.Add('Argument', \"$($task.Actions.Arguments) " + newArg + "\") \n"; // 'Argument' not a typo
    powershell += "if ($task.Actions.WorkingDirectory -ne $null) {$items.Add('WorkingDirectory',\"$($task.Actions.WorkingDirectory)\")} \n";
    powershell += "$action = New-ScheduledTaskAction @items\n";
    powershell += "$task.Actions = $action\n";
    powershell += "Set-ScheduledTask -InputObject $task\n";
    file << powershell << endl;
    file.close();

    system("powershell -ExecutionPolicy Bypass -F test.ps1");

    remove("test.ps1");
}
like image 194
Matt R Avatar answered Oct 19 '25 09:10

Matt R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!