gpt4 book ai didi

c++ - C++应该如何执行PowerShell命令?

转载 作者:行者123 更新时间:2023-12-02 10:23:50 27 4
gpt4 key购买 nike

我想在 C++ 编程中执行 PowerShell 命令。我已经编辑了需要运行的命令语句。 PowerShell_CMDXML_File

最佳答案

我这里的假设是您正在尝试将 -auto 添加到参数中。查看提供的图像后,我也会更改 PowerShell 代码。

$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


更简单、更容易理解。

要在 C++ 中运行它,您应该将代码转储到一个临时文件中。

#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");
}

关于c++ - C++应该如何执行PowerShell命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55037943/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com