Power Shell HelperRun Script Text 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> RunScriptTextAsync(
string scriptText,
string? arguments = null,
string? workingDirectory = null,
string executionPolicy = "Bypass",
CancellationToken cancellationToken = default
)参数
- scriptText String
- 要执行的脚本内容(可多行)。
- arguments String (Optional)
- 传给脚本的参数(原样拼接,注意自行转义)。
- workingDirectory String (Optional)
- 工作目录;为 null 时使用临时文件所在目录。
- executionPolicy String (Optional)
- 执行策略,默认 "Bypass"。
- cancellationToken CancellationToken (Optional)
- 取消令牌。
返回值
TaskPowerShellHelperPsResult包含退出码、标准输出和标准错误的 PowerShellHelperPsResult。
备注
实现方式:把脚本写入临时 .ps1 文件(使用 OutputEncoding,默认 GBK)后用 -File 执行, 避免 -Command 的引号转义问题,退出码语义也与文件执行完全一致。
执行结束后(无论成功、失败还是异常)自动删除临时文件。
此方法适合包含引号、多语句、中文等复杂内容的脚本; 简单单行命令可用 ExecuteCommandAsync(String, String, String, CancellationToken)。
异常
| ArgumentNullException | scriptText 为 null。 |