【问题标题】:Run external Powershell scripts form Dart从 Dart 运行外部 Powershell 脚本
【发布时间】:2021-06-21 00:24:03
【问题描述】:

在尝试从外部 Powershell 脚本传递和返回值时,Dart 不执行 Powershell 脚本(尝试使用 cmdpowershell)并且只返回 runtimeType Instance of 'ProcessResult'

有没有办法与外部 Powershell 脚本通信?

Dart2Ps.dart

import 'dart:io';

void main() async {
  // With Cmd
  var script_cmd = 'type "F:\Script\Dart\dart_tests\process\SumScript.ps1" | powershell.exe -c -';
  List<int> args = [1, 2];
  var sum_cmd = await Process.run('cmd', ['args', script_cmd]);
  stdout.write(sum_cmd.stdout);
  print(sum_cmd);

  // With Powershell
  var script_ps =
      'powershell -File "F:\Script\Dart\dart_tests\process\SumScript.ps1"';
  var sum_ps = await Process.run('powershell', ['args', script_ps]);
  stdout.write(sum_ps.stdout);
  print(sum_ps);
} 

SumScript.ps1

$sum = $args[0] + $args[1] 

Write-Host '$sum from Powershell'

return $sum

【问题讨论】:

    标签: powershell dart command-line


    【解决方案1】:

    确保将 dart+powershell 文件放在 dart /lib 文件夹中。

    飞镖代码:

    import 'dart:io';
    
    void main() {
      print(runPowerShellScript(r'C:\tmp\SumScript.ps1', ['1', '2']));
      // $sum from Powershell
      // 3
    }
    
    String runPowerShellScript(String scriptPath, List<String> argumentsToScript) {
      return Process.runSync(
              'Powershell.exe', ['-File', scriptPath, ...argumentsToScript]).stdout
          as String;
    }
    

    Powershell 代码:

    $sum = $args[0] + $args[1]  
    Write-Host '$sum from Powershell' 
    return $sum
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 2018-08-14
      • 1970-01-01
      • 2012-07-13
      • 2019-12-02
      相关资源
      最近更新 更多