Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a Powershell script from c#

Tags:

c#

powershell

I'm trying to run a PowerShell script from C# code, but I'm having some (maybe environmental) issues:

On a machine where I try to run it, the following occur:

  1. PowerShell starts and loads as Admin
  2. PowerShell window immediately closes (apparently) without error

Notes:

  • The script works. When I run it from ISE, it runs without errors.
  • If I right click the script and choose Run with PowerShell, I get a Execution Policy error even though I don't change it in the script.

Set-ExecutionPolicy : Windows PowerShell updated your execution policy successfully, but the setting is overridden by a policy defined at a more specific scope. Due to the override, your shell will retain its current effective execution policy of RemoteSigned. Type "Get-ExecutionPolicy -List" to view your execution policy settings. For more information please see "Get-Help Set-ExecutionPolicy". At line:1 char:46 + if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : PermissionDenied: (:) [Set-ExecutionPolicy], SecurityException + FullyQualifiedErrorId : ExecutionPolicyOverride,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand

  • Get-ExecutionPolicy -List

         Scope                ExecutionPolicy
         -----                ---------------
     MachinePolicy              Unrestricted
        UserPolicy                 Undefined
           Process                    Bypass
       CurrentUser              Unrestricted
      LocalMachine              Unrestricted
    
  • I believe that this is environmental because:

    • It ran fine a few days ago
    • It runs fine on other computers

This is the code I use to invoke the script:

if (File.Exists("Start.ps1"))
{
    string strCmdText = Path.Combine(Directory.GetCurrentDirectory(), "Start.ps1");

    var process = System.Diagnostics.Process.Start(@"C:\windows\system32\windowspowershell\v1.0\powershell.exe ", strCmdText);
    process.WaitForExit();
}

The script itself is irrelevant, as I have changed it to a simple

Write-Host "Hello"
$d=Read-Host

and I have the same issue.

like image 735
Ioana Nicu Avatar asked Jun 15 '15 11:06

Ioana Nicu


People also ask

How do I run a PowerShell script?

In File Explorer (or Windows Explorer), right-click the script file name and then select "Run with PowerShell". The "Run with PowerShell" feature starts a PowerShell session that has an execution policy of Bypass, runs the script, and closes the session.

Can I run a PowerShell script on a remote computer?

Using the WS-Management protocol, Windows PowerShell remoting lets you run any Windows PowerShell command on one or more remote computers. You can establish persistent connections, start interactive sessions, and run scripts on remote computers.

How do I run an unsigned PowerShell script?

Scenario/Problem: You need to be able to run unsigned scripts within PowerShell. Solution: Use the Set-ExecutionPolicy command. You are prompted with a confirmation. Enter Y and press Enter (or just press Enter— Y is the default).


1 Answers

The problem was in the path of the script. It had spaces on this particular machine and I had not handled that.

The window closed too fast to see any error but setting

process.StartInfo.RedirectStandardOutput = true;

helped me catch it.

The execution policy had nothing to do with my error.

To fix it I changed the path in the c# code like explained here: Executing a Powershell script in CMD.EXE from a location with "Illegal characters in path"

Complete code:

if (File.Exists("Start.ps1"))
            {
                File.GetAttributes("Start.ps1");
                string strCmdText =   Path.Combine(Directory.GetCurrentDirectory(), "Start.ps1");
                var process = new Process();
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.FileName = @"C:\windows\system32\windowspowershell\v1.0\powershell.exe";
                process.StartInfo.Arguments = "\"&'"+strCmdText+"'\"";

                process.Start();
                string s = process.StandardOutput.ReadToEnd();
                process.WaitForExit();

                using (StreamWriter outfile = new StreamWriter("StandardOutput.txt", true))
                {
                    outfile.Write(s);
                }

            }
like image 130
Ioana Nicu Avatar answered Oct 19 '22 07:10

Ioana Nicu