在Visual Studio的后期构建事件中运行PowerShell .ps1文件

8

我正在尝试执行以下的后期构建事件代码,但是我遇到了一个无用的错误:

"c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -file "$(SolutionDir)tools\nuget_pack.ps1"

在尝试之前,我已运行了以下 PowerShell 脚本:

Set-ExecutionPolicy unrestricted

我错过了什么?

更新

很奇怪,现在在VS上没有出现错误。但是脚本没有起作用。当我在powershell控制台中运行它时,会出现以下错误:

enter image description here


2
没有用的错误?如果不知道您遇到了什么问题,几乎不可能回答。 - Jamiec
1
无法回答这个问题,但我为您找到了一个有用的链接:http://davidfrette.wordpress.com/2011/01/20/creating-powershell-pre-build-and-post-build-events-for-visual-studio-projects/ - Jamiec
3个回答

17

Visual Studio会将后构建事件脚本写入一个 .BAT 文件,并使用 cmd.exe 执行该文件。因此,使用 & "<path-to-powershell>" 是行不通的。只需执行以下命令:

Powershell.exe -file "$(SolutionDir)tools\nuget_pack.ps1"

如果您认为其他构建解决方案的机器可能会遇到执行策略问题,请考虑采用此方法:

Powershell.exe -ExecutionPolicy Unrestricted -file "$(SolutionDir)tools\nuget_pack.ps1" 

我的错,忘记了批处理文件,也忘记了 OP 已经在 Powershell 控制台中尝试过它。所以文件部分应该是 $($SolutionDir)(我将其从 OP 的初始值更改为 PS),但我想 VS / MSBuild 需要以不同的方式呈现?$(SolutionDir) - manojlds
没问题。是的,应该是 $(SolutionDir)。这是在 MSBuild 中引用属性的方法。已修复。谢谢。 - Keith Hill
根据http://technet.microsoft.com/en-us/library/hh847736.aspx的说明,"文件必须是命令中的最后一个参数",因此应该这样写:
Powershell.exe -ExecutionPolicy Unrestricted -file "$(SolutionDir)tools\nuget_pack.ps1"
顺便说一下,由于这个规定,你可以向ps1添加参数。
- Andrzej Martyna

9
你可以在 Powershell 中重现错误,步骤如下:
"this is a string" -file "my.ps1"

这里的意思是把第一个参数作为字符串,-file 作为 -f 格式标志,并且说在格式替换的右侧没有值表达式。

请尝试像这样:

& "c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -file "$(SolutionDir)tools\nuget_pack.ps1"

(正如 Keith 所指出的那样,这不会起作用,因为它是从批处理文件而不是 Powershell 运行的。)

或者只需:

powershell.exe -file "$(SolutionDir)tools\nuget_pack.ps1"

问题出在"c:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"这个路径上了吗? - tugberk
@tugberk - 它被视为字符串。请查看我的更新答案,给出了您可以尝试的建议。 - manojlds
我可以让它正常工作,直到我有带空格的参数。如果我的参数中有空格,我该如何调用它? - Rhyous

1
在从Visual Studio调用PowerShell脚本之前,需要从PowerShell窗口将ExecutionPolicy设置为unrestricted,如下所示...
Set-ExecutionPolicy -Scope CurrentUser;
ExecutionPolicy: unrestricted;

以下是调用PowerShell脚本的方式...
powershell.exe $(SolutionDir)Setup.ps1 -SolutionDir $(SolutionDir) -ProjectPath $(ProjectPath)

enter image description here

然后在脚本中,您始终可以像这样读取参数...

param([string]$SolutionDir,
     [string]$ProjectPath);
#Write-Host ($SolutionDir +" Call this script with following aruments");
#Write-Host ($ProjectPath +" Call this script with following aruments");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接