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

3

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


1
这样的代码怎么样:system("powershell 'echo \"hello from powershell\"'");?不过我不知道对于比这更复杂的东西有多实用... - Blaze
1
我认为对于像您图像中展示的这样复杂的内容,倾向于导出一个临时的ps1文件是明智的。接着,可以将@Blaze的答案调整为“system("powershell -f temp.ps1");” - Matt R
1个回答

1
我这里的假设是您正在尝试将-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");
}

1
当脚本被禁用时,我调用system()执行命令,通过使用命令“Set-executionpolicy remotesigned”更改了设置,但只有在右键单击PowerShell时才能这样做。 - kevin
那你的意思是说我们不能使用“-f file.ps1”吗? - Matt R
是的,我不知道为什么要使用System()来执行禁用提示,手动右键点击就可以了。 - kevin
我上传了另一个XML文件图表,想要增加节点的红色部分,不使用PowerShell实现,你能帮我编写命令语句来增加这个节点吗? - kevin
我已经添加了一个绕过ExecutionPolicy的方法,并且如果存在现有值,则将其复制。这应该可以运行并在“newArg”字符串中添加任何您喜欢的参数。 - Matt R
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接