在使用参数构建后调用powershell脚本

Den*_*s G 7 powershell build-process visual-studio-2010 sharepoint-2010

我试图让Powershell在post post中运行我的PS脚本 - 但不知何故它不能像它应该的那样工作:

在Post-Build中执行以下命令:

C:\WINDOWS\system32\windowspowershell\1.0\powershell.exe
  -Command "& $(MSBuildProjectDirectory)\CreateSite.ps1 'auto'"
Run Code Online (Sandbox Code Playgroud)

(插入换行符以便更好地阅读)

该命令成功执行powershell脚本,但它不能做的是运行(从构建输出)命令:Rund Post-Build命令:

Add-PSSnapin : No snap-ins have been registered for Windows PowerShell version 2
At C:\path\CreateSite.ps1:4 char:
38
+ Add-PsSnapin <<<< Microsoft.SharePoint.PowerShell}
+ CategoryInfo : InvalidArgument: (Microsoft.SharePoint.PowerShell:String) [Add-PSSnapin], PSArgumentException
+ FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.AddPSSnapinCommand
Run Code Online (Sandbox Code Playgroud)

接下来是很多错误,因为所有后续命令都需要Sharepoint Snap-In.

  • 从cmd运行powershell C:\ path\CreateSite.ps1 auto时 - 一切正常.
  • 打开powershell.exe并运行C:\ path\CreateSite.ps1 auto时 - 一切正常.
  • 右键单击CreateSite.ps1 - >使用powershell运行 - 一切正常.

脚本中的相关行很简单Add-PsSnapin Microsoft.SharePoint.PowerShell.

我怎样才能运行darn脚本(并让它包含PSSnapIn)在Visual Studio后期版本中传递一个参数?

小智 16

(这个帖子并不新鲜,但是我从谷歌来到这里,所以我认为分享我发现的解决方案会让其他人感兴趣)

我尝试将powershell.exe的路径更改为"%WINDIR%\ SysNative\WindowsPowerShell\v1.0\powershell.exe",它完美无缺.从Post Build事件调用64位版本,并成功添加SharePoint管理单元.

致本文的致谢:http://msdn.microsoft.com/en-us/library/ff798298.aspx,"使用Windows PowerShell脚本在Visual Studio中自动执行任务".

  • +1非常优雅,实际上是正确的解决方案!感谢分享. (2认同)

Kei*_*ill 6

由于文件系统虚拟化,您无法从32位进程(即承载msbuild引擎的Visual Studio)中真正指定64位版本PowerShell的路径.解决此问题的一种解决方法是创建一个64位启动程序,该启动程序以64位运行,并将启动64位版本的PowerShell.这是一个简单的C#程序,它将执行此操作:

using System;
using System.Diagnostics;

class App
{
  static int Main(string[] args)
  {
    Process process = Process.Start("PowerShell.exe", String.Join(" ", args));
    process.WaitForExit();
    return process.ExitCode;
  }
}
Run Code Online (Sandbox Code Playgroud)

一定要将其编译为64位,如下所示:

csc .\PowerShell64.cs /platform:x64
Run Code Online (Sandbox Code Playgroud)

然后,从您的构建后事件执行此启动程序exe将其传递给您要调用64位PowerShell的参数.另外,使用PowerShell 2.0我建议使用File参数来执行脚本,例如:

c:\path\PowerShell64.exe -File "$(MSBuildProjectDirectory)\CreateSite.ps1" auto
Run Code Online (Sandbox Code Playgroud)

也就是说,肯定还有一些其他方式(实用程序)可以从64位进程启动exes.