Power Shell HelperExecute Command Async 方法
异步执行一段内联 PowerShell 命令并获取输出。
Definition
命名空间: Suresking.Utility
程序集: Suresking.Utility (在 Suresking.Utility.dll 中) 版本:1.3.22+a27276bb8ffde055e69ff608e98aafba279e1e99
包含退出码、标准输出和标准错误的 PowerShellHelperPsResult。
程序集: Suresking.Utility (在 Suresking.Utility.dll 中) 版本:1.3.22+a27276bb8ffde055e69ff608e98aafba279e1e99
C#
public static Task<PowerShellHelperPsResult> ExecuteCommandAsync(
string command,
string? workingDirectory = null,
string executionPolicy = "Bypass",
CancellationToken cancellationToken = default
)参数
- command String
- 要执行的命令字符串(通过 -Command 传入)。
- workingDirectory String (Optional)
- 工作目录;为 null 时使用当前进程的工作目录。
- executionPolicy String (Optional)
- 执行策略,默认 "Bypass"。
- cancellationToken CancellationToken (Optional)
- 取消令牌;取消时会终止整个进程树并重新抛出 OperationCanceledException。
返回值
TaskPowerShellHelperPsResult包含退出码、标准输出和标准错误的 PowerShellHelperPsResult。
备注
命令内部的引号会被替换为 \" 进行简单转义,但该转义并不完备(例如反引号转义、嵌套引号等)。 若命令中带引号、多语句或复杂表达式,强烈建议改用 RunScriptTextAsync(String, String, String, String, CancellationToken), 后者通过临时 .ps1 文件执行,无引号转义问题。
此方法没有同步版本;如需同步调用可自行 GetAwaiter().GetResult(),但要注意死锁风险。