我正在尝试在 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");
}
}
不幸的是,这种方法不起作用。我该如何让它发挥作用?
非常感谢。