Visual Studio 2015生成后事件运行ps1脚本报退出码1如何解决
问题描述
需要在Visual Studio 2015项目构建成功后,自动运行存放在项目目录下的Deploy.ps1PowerShell脚本。
此前在Visual Studio 2019环境中,直接在项目属性-生成事件-生成后事件命令行中添加如下命令即可正常运行:
powershell -ExecutionPolicy Unrestricted $(ProjectDir)Deploy.ps1
在Visual Studio 2015中使用完全相同的配置(脚本存放位置、生成后事件命令完全一致)时,每次构建都会失败,提示命令退出代码为1,报错日志如下:
1>------ Build started: Project: portdemo2, Configuration: Debug Any CPU ------ 1> portdemo2 -> C:\Users\320178017\Documents\Visual Studio 2015\portdemo2\portdemo2\bin\Debug\portdemo2.dll 1> C:\Users\320178017\Documents\Visual : The term 'C:\Users\320178017\Documents\Visual' is not recognized as the name of 1> a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, 1> verify that the path is correct and try again. 1> At line:1 char:1 1> + C:\Users\320178017\Documents\Visual Studio 2015\portdemo2\portdemo2\D ... 1> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1> + CategoryInfo : ObjectNotFound: (C:\Users\320178017\Documents\Visual:String) [], CommandNotFoundExceptio 1> n 1> + FullyQualifiedErrorId : CommandNotFoundException 1> 1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(4714,5): error MSB3073: The command "powershell -ExecutionPolicy Unrestricted C:\Users\320178017\Documents\Visual Studio 2015\portdemo2\portdemo2\Deploy.ps1" exited with code 1. ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
故障根因是项目路径包含空格:路径中Visual Studio字段的空格导致传入PowerShell的路径被截断,系统仅识别到C:\Users\320178017\Documents\Visual片段,无法找到目标脚本。此前尝试直接用双引号包裹$(ProjectDir)Deploy.ps1路径未解决问题。
可行解决方案
Visual Studio 2019及以上版本的生成后事件会自动为带空格的宏替换值添加隐式引号包裹,因此不加显式引号和参数也能正常运行,VS2015没有这个隐式处理逻辑,必须显式按以下格式配置命令:
- 方案1(推荐):添加
-File参数明确指定要运行的脚本文件,同时用英文半角双引号包裹完整脚本路径,生成后事件命令如下:
powershell -ExecutionPolicy Unrestricted -File "$(ProjectDir)Deploy.ps1"
加上-File参数后,PowerShell会将后续引号内的内容识别为完整的脚本文件路径,不会按空格截断。之前直接加引号不生效,是因为未指定-File参数时,PowerShell默认把传入内容当作命令语句解析,VS生成事件的多层转义会把直接添加的双引号吞掉,最终传给PowerShell的还是不带引号的截断路径。
- 方案2:使用PowerShell调用运算符+单引号包裹路径,命令如下:
powershell -ExecutionPolicy Unrestricted "& '$(ProjectDir)Deploy.ps1'"
单引号不会被VS2015生成事件的转义逻辑吞掉,配合调用运算符&,可以保证带空格的路径被完整识别为脚本文件位置。
- 配置校验技巧:写完命令后,可以点击生成后事件编辑窗口的「宏」按钮,查看
$(ProjectDir)的实际展开值,确认宏末尾自带路径反斜杠,不会出现路径和Deploy.ps1拼接错误的问题。
内容的提问来源于stack exchange,提问作者POVR2

