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

批处理文件中如何带参数执行PowerShell脚本?

问题原因

你现有的写法将脚本路径和待传递参数全部包裹在了-File参数的同一组双引号内,PowerShell会把C:\Public\File\SomeScript.ps1 Arg1 %1 Arg2 %2 Arg3 %3 Arg4 %4整个字符串识别为脚本文件的路径,找不到对应文件就会静默退出,所以没有执行反应。

修正后的完整代码
@echo off
echo %1
echo %2
echo %3
echo %4
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\Public\File\SomeScript.ps1"" Arg1 ""%~1"" Arg2 ""%~2"" Arg3 ""%~3"" Arg4 ""%~4""' -Verb RunAs}"
核心修改说明
  • 把-File对应的脚本路径单独用两对双引号包裹,和后续参数拆分,符合PowerShell的-File参数语法规则:-File "脚本路径" 参数1 参数2 ...
  • 用%~1替代原有的%1,会自动去除批处理接收到的参数自带的外层引号,避免参数包含空格时出现引号嵌套混乱的问题
  • 每个批处理参数外层额外包裹两对双引号,确保参数携带空格、特殊符号时也能正常传递到PowerShell脚本中
调试排查方案

如果修改后依然有异常,可以暂时去掉-Verb RunAs提权参数,同时给第二个PowerShell进程添加-NoExit参数,执行后窗口不会自动关闭,可直接查看报错信息定位问题:

PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoExit -NoProfile -ExecutionPolicy Bypass -File ""C:\Public\File\SomeScript.ps1"" Arg1 ""%~1"" Arg2 ""%~2"" Arg3 ""%~3"" Arg4 ""%~4""'}"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:06:05