Running a powershell script as a post-build event in Visual Studio fails despite the fact that that same script runs fine from the commandline. Why is this?
-
Any chance to show the script and explaining what you mean by *failing* (error message, actual behavior differs then expected behavior - in this case please describe both, something else)? – Darin Dimitrov Oct 30 '11 at 21:13
-
Sorry, I don't expect an answer to this question! I already have an answer, just it was hard to find and not on SO so I have put a question here and answered it myself! – Alan Christensen Oct 30 '11 at 21:15
-
The error for me was really obscure "The System cannot Execute the specified program" – Alan Christensen Oct 30 '11 at 21:17
-
It also was a kind of duplicate of [Post build event execute powershell](http://stackoverflow.com/questions/6500320/post-build-event-execute-powershell/6501719#6501719) – JPBlanc Oct 31 '11 at 06:45
3 Answers
Sorry for re-animating an ancient question but since my search lead me to this post and my resolution was slightly different I wanted to add it.
In my case the issue was with Visual Studio 2017 CE on Windows 10 1903 and the symptom was a failure to run a powershell script as a post-build event even though the same powershell ran without error from the command line with the same privileges.
I was getting an exited with error 1 but could see the script was not actually being run.
VS was using the 32 bit version (not the 64 as per the accepted answer to the question) and it was that build of powershell that I'd not set the exectution policy on.
I ran PowerShell (x86) and Set-ExecutionPolicy Unrestricted, then my post-build tasks ran fine.

- 1,006
- 10
- 17
Answering my own question just to save others the pain of researching this.
Well http://www.vistax64.com/powershell/205436-running-powershell-post-build-event-ignoring-executionpolicy.html suggests that despite Visual Studio being 32 bit, it runs the 64 bit version of powershell which is independent.
The reality seems that Visual Studio runs the Windows\syswow64 version of Powershell (32 bit!?) while your normal Powershell command prompt will default to the Windows\system32 version (64 bit?!). You need to set execution policy etc for that separately.

- 817
- 6
- 11
(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: https://learn.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ff798298(v=office.14), "Using Windows PowerShell Scripts to Automate Tasks in Visual Studio".

- 10,297
- 11
- 59
- 88

- 181
- 1
- 4