I'm trying to get Powershell to run my PS script in post built - but somehow it doesn't work like it's supposed to:
Following command in Post-Build:
C:\WINDOWS\system32\windowspowershell\1.0\powershell.exe
-Command "& $(MSBuildProjectDirectory)\CreateSite.ps1 'auto'"
(inserted line break for better reading)
The command executes the powershell script sucessfully, but what it can't do is run the commands within (Output from Build): Rund Post-Build Command:
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
And following that are many errors because all subsequent commands need the Sharepoint Snap-In.
The relevant line in the script is simply Add-PsSnapin Microsoft.SharePoint.PowerShell
.
How can I just run the darn script (and get it to include the PSSnapIn) passing it a parameter in Visual Studio post-build?
(This thread is not new, but I got here from Google, so I thought sharing the solution I found would be interesting to others)
I tried changing the path to powershell.exe to "%WINDIR%\SysNative\WindowsPowerShell\v1.0\powershell.exe" and it worked perfect. The 64 bits version is called from the Post Build event and it successfully adds the SharePoint snapin.
Credits to this article: http://msdn.microsoft.com/en-us/library/ff798298.aspx, "Using Windows PowerShell Scripts to Automate Tasks in Visual Studio".
Because of file system virtualization, you can't really specify the path to the 64-bit version of PowerShell from a 32-bit process (ie Visual Studio - which hosts the msbuild engine). One hack-ish way to work around this is to create a 64-bit launcher that runs as 64-bit and will launch the 64-bit version of PowerShell. Here's a simple C# program that will do this:
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;
}
}
Be sure to compile this as 64-bit like so:
csc .\PowerShell64.cs /platform:x64
Then, from your post-build event execute this launcher exe passing it the parameters you want to invoke 64-bit PowerShell with. Also, with PowerShell 2.0 I would recommend using the File
parameter to execute a script e.g.:
c:\path\PowerShell64.exe -File "$(MSBuildProjectDirectory)\CreateSite.ps1" auto
That said, surely there has to be some other way (utility) that launches exes from a 64-bit process.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With