How to launch powershell script in C#

If you want to start a powershell script in a CSharp application, you don’t have to construct a cmd command line to start the script.

You can use the following example to make your life easier:

The variable “script” is the full path to the powershell script.
The variable “parameters” is an instance of an IDictionary type, which contains a set of parameter keys/values.

            using (var powerShellInstance = PowerShell.Create())
            {
                //Prepare powershell execution
                powerShellInstance.AddCommand(script);
                powerShellInstance.AddParameters(parameters);

                //Execute powershell command and get the results
                var results = powerShellInstance.Invoke();

                var errors = powerShellInstance.Streams.Error;
                var sb = new StringBuilder();

                if (errors.Count > 0)
                {
                    foreach (var error in errors)
                    {
                        sb.Append(error);
                    }
                    errorResult = sb.ToString();
                }
                else
                {
                    foreach (var result in results)
                    {
                        sb.AppendLine(result.ToString());
                    }
                    executionResult = sb.ToString();
                }

                return errors.Count == 0;
            }

Update:2015-07-01
I’m having a problem executing a powershell script in the logon server.
Actually, the application uses a system account to execute the powershell script.
But the account does not have enough privileges to run the script.

The exception is:PSSecurityException
Here are the details of the error:

Message: AuthorizationManager check failed.
InnerException stack trace:    
at System.Management.Automation.AuthorizationManager.ShouldRunInternal(CommandInfo commandInfo, CommandOrigin origin, PSHost host)
InnerException: A command that prompts the user failed because the host program or the command type does not support user interaction. The host was attempting to request confirmation with the following message: Run only scripts that you trust. While scripts from the internet can be useful, this script can potentially harm your computer. Do you want to run xxx.ps1?

I searched the internet for information. It is so important to repeat the same mistakes! First, I copied the service account into the integrated environment by removing it from the “Administrators” group.
You can go to the “Local Users and Groups”, then “Groups”, then “Administrators” group. Select the service account and delete it from the group. Well, I found that the problem is related to the enforcement policy on the server. I’ve tested it with the enforcement policy.
You can use open powershell.exe on the server.
Execute the command:

Get-ExecutionPolicy

You can even verify that a particular user is enforcing the policy.
You will need to open powershell.exe from your service account to run it.
Then execute the command:

Get-ExecutionPolicy -Scope:CurrentUser

 

In my server, the enforcement policy is set to unlimited in the LocalMachine range.

There are 7 enforcement policies in total.
Default:This is equal to Restricted
Restricted: Do not load configuration files or run scripts. This is the default.
AllSigned: Requires all scripts and configuration files to be signed by a trusted publisher, including scripts written on your local machine.
remotesizable: Requires all scripts and configuration files downloaded from the Internet to be signed by a trusted publisher.
unrestricted:Load all configuration files and run all scripts. If you run an unsigned script downloaded from the internet, you will be prompted for permission before running the script.
Bypass: No blocking, warnings or prompts.
Undefined:Deletes the currently assigned enforcement policy from the current scope. This parameter does not delete enforcement policies set within the Group Policy range.

0 has 5 ranges:
Process
CurrentUser
LocalMachine
UserPolicy
MachinePolicy

0 is actually the enforcement policy preventing the service account from running the script correctly. So I need to change the enforcement policy. In the end, the bypass method meets my needs. But I don’t apply this enforcement policy to all types of users within the local machine. So I only apply the bypass enforcement policy to the service account.

The commands used are:

Set-ExecutionPolicy -Scope:CurrentUser -ExecutionPolicy:Bypass

Read More: