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

Web应用向PowerShell传命令报错:文件不存在问题求助

问题排查与解决

问题现象

  • 期望执行的PowerShell命令:
    .\send-message.ps1 -filename "CurrentUnloadingPlaning20240320142613833.json" -queuePath "FormatName:DIRECT=OS:GTH-RCWEB.NOVELIS.BIZ\private$\srs_pdi"
    
  • C#构建后的命令:
    ".\send-message.ps1 -filename "CurrentUnloadingPlaning20240320152128068.json" -queuePath "FormatName:DIRECT=OS:server\private$\srs_pdi""
    
  • 执行错误:

    \msmq-powershell-test\send-message.ps1 : 文件'\CurrentUnloadingPlaning20240320152128068.json'不存在。
    At line:1 char:1

核心原因

  1. 脚本路径错误:C#中@"\.\send-message.ps1"多了前置的\,导致PowerShell从根目录查找脚本,进而让文件名的相对路径被错误解析为绝对路径(开头的\)。
  2. 引号转义失效:直接拼接双引号时,外层引号被PowerShell剥离后,文件名参数失去引号包裹,路径解析逻辑出错。
  3. 队列路径拼写错误:C#代码中把FormatName:DIRECT=OS:写成了FormatName:DIRECT=OS server,缺少了关键的冒号,会导致队列参数无效。

修复后的C#代码

方案1:用单引号包裹参数(更简洁,避免转义问题)

string nameFile = "CurrentUnloadingPlaning" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".json";
// 用单引号作为PowerShell字符串边界,无需复杂转义
string filenameArg = $"'{nameFile}'";
string queuePathArg = @"'FormatName:DIRECT=OS:server\private$\srs_pdi'";
// 脚本路径去掉前置的\,确保是相对路径
string command1 = $".\\send-message.ps1 -filename {filenameArg} -queuePath {queuePathArg}";

方案2:正确转义双引号

string nameFile = "CurrentUnloadingPlaning" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".json";
// 用转义双引号包裹参数
string filenameArg = $"\"{nameFile}\"";
string queuePathArg = @"\""FormatName:DIRECT=OS:server\private$\srs_pdi\""";
string command1 = $".\\send-message.ps1 -filename {filenameArg} -queuePath {queuePathArg}";

额外注意事项

如果Web应用运行在IIS等环境,PowerShell的当前工作目录可能不是脚本所在目录,建议直接指定JSON文件的绝对路径,避免相对路径问题:

// 获取应用程序根目录
string appRoot = AppDomain.CurrentDomain.BaseDirectory;
// 拼接JSON文件的绝对路径
string filePath = Path.Combine(appRoot, nameFile);
string filenameArg = $"\"{filePath}\"";
string queuePathArg = @"'FormatName:DIRECT=OS:server\private$\srs_pdi'";
string command1 = $".\\send-message.ps1 -filename {filenameArg} -queuePath {queuePathArg}";

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 14:47:09