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

标签 c++ powershell

我想在 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/

相关文章:

powershell - 如何在Powershell中使用While循环?

powershell - 在powershell中搜索文字连字符

c++ - 如何为 vector 分配元素?

c++ - cuda示例代码中的.raw文件格式是什么?

c++ - ADSI 使用 C++ 过滤 OU 中的所有计算机

.net - Powershell - 在不安装 Excel 的情况下将 CSV 转换为 XLS

sharepoint - 如何在不安装 sharepoint 的情况下使用 Sharepoint cmdlet?

c++ - 如何从文件中读取值。分词器

c++ - 对具有许多模板参数的类进行操作

node.js - 是否可以在 Firebase 托管的 Web 应用程序上安装 powershell?