You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#调用PowerShell执行Program Files (x86)下脚本报错如何解决

问题根因

你使用的PowerShell.AddScript()方法会将输入字符串直接作为PowerShell代码执行,传入带空格的文件路径时,PowerShell会按空格拆分指令,将路径中的x86识别为未定义的独立命令,因此抛出报错。

修复方案

方案1:使用AddCommand方法加载脚本文件(推荐)

这是调用外部ps1脚本的标准写法,无需手动处理路径转义:

r.Open();
using(PowerShell ps = PowerShell.Create()) {
    ps.Runspace = r;
    // 改用AddCommand直接指定脚本文件路径
    ps.AddCommand(_scriptPath);
    ps.Invoke();
    // 后续错误处理逻辑保持不变
    if (ps.HadErrors) {
        List<string> _items = new List<string>();
        var errorMessage = new StringBuilder();
        foreach (ErrorRecord err in ps.Streams.Error) {
            errorMessage.AppendLine(err.ToString());
        }
        _items.Add(errorMessage.ToString());
        foreach (var i in _items) {
            MessageBox.Show(i);
        }
    }
}

方案2:如果需要保留AddScript调用,手动处理路径转义

需要在路径外层包裹引号,同时加调用运算符&告知PowerShell这是要执行的文件:

// 对脚本路径做转义处理
string escapedScript = $"& '{_scriptPath}'";
using(PowerShell ps = PowerShell.Create().AddScript(escapedScript)) {
    // 其余逻辑保持不变
}

可选:脚本内路径使用优化

脚本中获取到路径后,执行Copy-Item等操作时如果涉及变量拼接路径,建议用双引号包裹路径参数,避免空格引发二次报错:

$ScriptPath = Split-Path $Script:MyInvocation.MyCommand.Path
# 示例Copy操作,路径用双引号包裹
Copy-Item "$ScriptPath\源文件.txt" "目标路径"

内容的提问来源于stack exchange,提问作者Subscaper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 12:21:01