2

I have a powershell script, which works, since I have executed it manually on the server. But I cant get it to work from the C# code on one of our servers. It does work on two other computers, with the code, but not on the server where I need to execute it.

The code that executes the script:

var process = new Process();        
process = Process.Start("C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\Powershell.exe", "C:\\CC\\Script\\script.ps1");

I have tried with other variations but we are running PowerShell v1.0 and it doesnt support the solutions: https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/

Since the code works on two computer but not on the server where we need to use it, I checked the Execution Policy and it was "RemoteSigned" on all of them.

Any ideas what else it could be? Would it make any difference with another set of code and do you have any good examples of what code I could use instead, for PowerShell v1.0? Any other policies that could make the difference?

Thnx in advance

Jack P
  • 99
  • 10
  • 1
    Do you get an error message? – stuartd Jan 19 '17 at 11:02
  • I dont have the exact error message atm. But I printed the standard error in the C# code and it just said that the process never had been started. Allso the script itself creates a folder with process information, but no folder is created. So, the script is never executed at all. Still I do not get any exception in my catch block and the exit code just gives me a "1". – Jack P Jan 19 '17 at 12:21
  • Does the account the script is running under have the appropriate permissions on that server? Anything applicable in the server event log? – stuartd Jan 19 '17 at 12:24

2 Answers2

2

use this command in powershell administrator privilege :

Set-ExecutionPolicy Bypass -Force

and also take care about the Script path to pass it correct to C#.

  • That's something I'd never do on a server. Especially not Bypass. – Joey Jan 19 '17 at 11:27
  • This is on one of our customers servers and they would never accept such a change. The execution policy is the same when we try it locally, and it works, so this should not be necessary? – Jack P Jan 19 '17 at 12:24
  • Instead of doing it on a global level, just do it for the single execution of the command Pass in the argument `"-ExecutionPolicy Bypass C:\\CC\\Script\\script.ps1"` and it will bypass the policy for this single session only. – Scott Chamberlain Jan 19 '17 at 15:57
0

Problem solved;

Managed to find the answer in another question at Stackoverflow, had the same problem as this person:

PowerShell says "execution of scripts is disabled on this system."

The execution policy was undefined for the x86 version.

Community
  • 1
  • 1
Jack P
  • 99
  • 10