0

Im creating a tool to execute scripts from Forms application. The prom is that even if i set my execution policies to unrestricted or remote signed to problem still persist

File C:\AAE\Scripts\script1.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170. File C:\AAE\Scripts\script2.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170.

these files are just some test scripts. which contains

#scriptfile
function Show-process {
    write-host "---------------------------------------------------------------------------------------------------------------------------------starting get process script"
    Get-Process *
    write-host "---------------------------------------------------------------------------------------------------------------------------------end get process script"
}
Show-process

this is the code in C#


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Windows.Forms;

namespace AAE___ICT_Support_Tool
{
    public partial class AAE_ICT_Support_Tool_Form : Form
    {
        private Dictionary<string, string>[] scriptDicts = new Dictionary<string, string>[2];
        public AAE_ICT_Support_Tool_Form()
        {
            InitializeComponent();

            // Create dictionaries with scripts and manual paths for each tab page
            scriptDicts[0] = new Dictionary<string, string>();
            scriptDicts[0].Add("Script 1", "C:\\AAE\\Scripts\\script1.ps1");
            scriptDicts[0].Add("Script 2", "C:\\AAE\\Scripts\\script2.ps1");

            scriptDicts[1] = new Dictionary<string, string>();
            scriptDicts[1].Add("Script 3", "C:\\AAE\\Scripts\\script3.ps1");
            scriptDicts[1].Add("Script 4", "C:\\AAE\\Scripts\\script4.ps1");

            // Create tab pages with names and add them to the tab control
            TabPage tabPage1 = new TabPage("Scripts 1-2");
            tabControl1.TabPages.Add(tabPage1);
            int yPos = 10;
            foreach (string scriptName in scriptDicts[0].Keys)
            {
                CheckBox cb = new CheckBox
                {
                    Text = scriptName,
                    AutoSize = true,
                    Location = new Point(10, yPos)
                };
                tabPage1.Controls.Add(cb);
                yPos += cb.Height + 5;
            }
            // Create tab pages with names and add them to the tab control
            TabPage tabPage2 = new TabPage("Scripts 3-4");
            tabControl1.TabPages.Add(tabPage2);
            yPos = 10;
            foreach (string scriptName in scriptDicts[1].Keys)
            {
                CheckBox cb = new CheckBox
                {
                    Text = scriptName,
                    AutoSize = true,
                    Location = new Point(10, yPos)
                };
                tabPage2.Controls.Add(cb);
                yPos += cb.Height + 5;
            }
        }
        private void Run_Btn_Click(object sender, EventArgs e)
        {
            // Get the selected scripts and their paths from all tab pages
            Dictionary<string, string> selectedScripts = new Dictionary<string, string>();
            foreach (TabPage tabPage in tabControl1.TabPages)
            {
                Dictionary<string, string> scriptDict = null;
                if (tabPage.Text == "Scripts 1-2")
                {
                    scriptDict = scriptDicts[0];
                }
                else if (tabPage.Text == "Scripts 3-4")
                {
                    scriptDict = scriptDicts[1];
                }
                if (scriptDict != null)
                {
                    foreach (Control c in tabPage.Controls)
                    {
                        if (c is CheckBox && ((CheckBox)c).Checked)
                        {
                            string scriptName = ((CheckBox)c).Text;
                            if (scriptDict.ContainsKey(scriptName))
                            {
                                selectedScripts.Add(scriptName, scriptDict[scriptName]);
                            }
                        }
                    }
                }
            }

            // Run the selected scripts
            string output = "";
            foreach (string scriptPath in selectedScripts.Values)
            {
                using (PowerShell ps = PowerShell.Create())
                {
                    ps.AddScript(scriptPath);
                    ps.Runspace = RunspaceFactory.CreateRunspace();
                    ps.Runspace.Open();
                    ps.AddCommand("Set-ExecutionPolicy").AddParameter("Scope", "Process").AddParameter("ExecutionPolicy", "Bypass");
                    PSDataCollection<PSObject> results = new PSDataCollection<PSObject>();
                    results.DataAdded += new EventHandler<DataAddedEventArgs>(delegate (object sender1, DataAddedEventArgs e1)
                    {
                        PSDataCollection<PSObject> source = (PSDataCollection<PSObject>)sender1;
                        output += source[e1.Index].ToString() + Environment.NewLine;
                    });
                    ps.Streams.Error.DataAdded += new EventHandler<DataAddedEventArgs>(delegate (object sender1, DataAddedEventArgs e1)
                    {
                        PSDataCollection<ErrorRecord> source = (PSDataCollection<ErrorRecord>)sender1;
                        output += source[e1.Index].ToString() + Environment.NewLine;
                    });
                    ps.Invoke(null, results);
                }
            }

            // Show the output in the textbox
            txtOutput.Text = output;
        }
    }
}

I've tried to run it in PowerShell ISE and the terminal it works fine. is something wrong when i click the run button in the forms. it seems that it maybe invoked incorrectly. Maybe someone can explain what is going on. also tried to bypass in the code and same issue persists.Forms app

also changed the scope to CurrentUser same happens.

how can I possibly resolve this :S

  • Does this answer your question? [PowerShell says "execution of scripts is disabled on this system."](https://stackoverflow.com/questions/4037939/powershell-says-execution-of-scripts-is-disabled-on-this-system) Also, did you go to the MS link provided in the error message? – Ken White Feb 20 '23 at 00:37
  • In short: PowerShell's effective [script-execution policy](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_Execution_Policies) also applies to use of the PowerShell _SDK_. While execution policies are primarily about `*.ps1` _files_, they may come into play _indirectly_ when (possibly (implicitly) importing a _module_, because `*.psm1` files (script modules) and formatting / type-definition files (`*.ps1xml`) are covered by the policy too. The linked duplicates show how to set the execution policy via the SDK, on a per-process basis. – mklement0 Feb 20 '23 at 02:07

0 Answers0