我正在尝试在 Flutter/Dart 中以管理员权限运行 Powershell 命令。该命令在临时目录中运行 .ps1 文件。
我找到了这篇文章,我实现了它并且它运行良好。但是,在 PowerShell 命令运行后,我在 PowerShell 窗口上看到一个输出,因此我希望打印此输出,但我什么也没得到。
Future<void> executePowerShellCommand() async {
String tempFilePath = '${Directory.systemTemp.path}\\COMMAND.ps1';
try {
String command = 'powershell';
List<String> args = [
'-Command',
'Start-Process -FilePath "powershell" -ArgumentList "-ExecutionPolicy Bypass -NoProfile -File `"$tempFilePath`"" -Verb RunAs -Wait'
];
final ProcessResult result = await Process.run(command, args, runInShell: true, stdoutEncoding: utf8, stderrEncoding: utf8);
String output = result.stdout.toString().trim();
String errorOutput = result.stderr.toString().trim();
int exitCode = result.exitCode;
if (exitCode == 0 && errorOutput.isEmpty) {
debugPrint('>>>Powershell Command succeeded: $output');//output is empty
}
} catch (e, s) {
debugPrint(">>>Error $e");
}
}
我研究后发现,这Start-Process
会生成一个单独的进程,这就是输出为空的原因。所以我想我可以捕获命令的输出并将其保存到文件中,然后读取文件的内容。
像这样:
Future<void> executePowerShellCommandWithOutput() async {
String tempFilePath = '${Directory.systemTemp.path}\\COMMAND.ps1';
String outputFilePath = '${Directory.systemTemp.path}\\OUTPUT.txt';
try {
String command = 'powershell';
List<String> args = [
'-Command',
'''Start-Process -FilePath "powershell" -ArgumentList '-ExecutionPolicy Bypass -NoProfile -File "$tempFilePath" | Out-File "$outputFilePath" -Encoding utf8' -Verb RunAs -Wait'''
];
final ProcessResult result = await Process.run(command, args, runInShell: true, stderrEncoding: utf8);
String errorOutput = result.stderr.toString().trim();
int exitCode = result.exitCode;
if (exitCode == 0 && errorOutput.isEmpty) {
File file = File(outputFilePath);
String fileContent = file.readAsString().toString();
debugPrint('>>>File Content: $fileContent');
}
} catch (e, s) {
debugPrint(">>>Error $e");
}
}
不幸的是,这种方法不起作用。我该如何让它发挥作用?
非常感谢。
为了使您的方法发挥作用,您必须使用
-Command
Windows PowerShell CLI,而不是-File
使用。powershell.exe
与 不同
-File
,它仅支持目标脚本路径(*.ps1
),后面可选跟文字传递参数,-Command
允许您传递PowerShell 源代码片段,这是执行整个管道(如您的管道)所必需的(... | Out-File ...
)请注意使用
-Command
而不是-File
,以及使用&
,调用文件*.ps1
(这是语法上的必要,因为脚本文件路径被引用了)。请注意,虽然尝试使用和参数直接捕获文件中的命令输出很诱人,但这
Start-Process
与结合使用时不起作用,即在启动提升的进程时 -有关详细信息,请参阅此答案。-RedirectStandardOut
-RedirectStandardError
-Verb RunAs