2

I have tried the following case from powershell terminal :

invoke-command -connectionuri "http://FullMachineName/wsman" -configuration "http
://schemas.microsoft.com/powershell/Microsoft.PowerShell" -credential "MachineName\Administrator" -filepath "C:\scripts\get
Users.ps1"

This is working fine. But when I am trying the same thing through invoke command from C# it is throwing the following exception :

System.Management.Automation.CmdletInvocationException was unhandled
  Message=File C:\scripts\getUsers.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.
  Source=System.Management.Automation
  WasThrownFromThrowStatement=false
  StackTrace:
       at System.Management.Automation.Internal.PipelineProcessor.SynchronousExecuteEnumerate(Object input, Hashtable errorResults, Boolean enumerate)
       at System.Management.Automation.Runspaces.LocalPipeline.InvokeHelper()
       at System.Management.Automation.Runspaces.LocalPipeline.InvokeThreadProc()
  InnerException: System.Management.Automation.PSSecurityException
       Message=File C:\scripts\getUsers.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.
       Source=System.Management.Automation
       WasThrownFromThrowStatement=false
       StackTrace:
            at System.Management.Automation.AuthorizationManager.ShouldRunInternal(CommandInfo commandInfo, CommandOrigin origin, PSHost host)
            at Microsoft.PowerShell.Commands.PSExecutionCmdlet.GetScriptBlockFromFile(String filePath)
            at Microsoft.PowerShell.Commands.PSExecutionCmdlet.BeginProcessing()
            at Microsoft.PowerShell.Commands.InvokeCommandCommand.BeginProcessing()
            at System.Management.Automation.Cmdlet.DoBeginProcessing()
            at System.Management.Automation.CommandProcessorBase.DoBegin()
       InnerException: System.UnauthorizedAccessException
            Message=File C:\scripts\getUsers.ps1 cannot be loaded because the execution of scripts is disabled on this system. Please see "get-help about_signing" for more details.
            InnerException: 

I am trying with the following code :

String file = @"C:\scripts\getUsers.ps1";
PowerShell ps = PowerShell.Create()
PSCommand cmd = new PSCommand();                
cmd.AddCommand("Invoke-Command");
cmd.AddParameter("CONNECTIONURI", "http://FullMachineName/wsman");
cmd.AddParameter("FILEPATH",file);
cmd.AddParameter("CREDENTIAL", Credential);            
cmd.AddParameter("CONFIGURATION","http://schemas.microsoft.com/powershell/Microsoft.PowerShell" );
ps.Commands = cmd;                
Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();
ps.Runspace = runSpace;
psObjects = ps.Invoke();

2 Answers 2

3

The typical problem in this scenario is that you have run Set-ExecutionPolicy in PowerShell for either the 32-bit or the 64-bit version of PowerShell but not both. The C# program you are running is likely the bit-ness where you haven't changed PowerShell's default execution policy. Try opening up both a 32-bit and a 64-bit PowerShell session and ensure the execution policy is set to RemoteSigned or Unrestricted.

Sign up to request clarification or add additional context in comments.

4 Comments

Tried with execution policy RemoteSigned and Unrestricted from 32 bit windows powershell.Still getting the same error.
Try compiling the app as x86.
I tried the invoke-command directly in a powershell 32 bit terminal and I am getting the exception mentioned in the question.
And if you run Get-ExecutionPolicy in that shell, does it return Restricted? If so, you need to run (in an elevated 32-bit PowerShell) Set-ExecutionPolicy Unrestricted.
0

Try Setting and Getting Set-ExecutionPolicy Unrestricted using PowerShell Instance.

 public static ICollection<PSObject> RunScriptText(string scriptFullPath, ICollection<CommandParameter> parameters = null)
        {
            var runspace = RunspaceFactory.CreateRunspace();
            runspace.Open();
            var pipeline = runspace.CreatePipeline();

            using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                var initial = InitialSessionState.CreateDefault();
                Console.WriteLine("Importing ServerManager module");
                initial.ImportPSModule(new[] { "ServerManager" });

                PowerShellInstance.Runspace = runspace;

                PowerShellInstance.AddScript("Set-ExecutionPolicy Unrestricted");
                PowerShellInstance.AddScript("Get-ExecutionPolicy");
                PowerShellInstance.Invoke();

                var cmd = new Command(scriptFullPath);
                if (parameters != null)
                {
                    foreach (var p in parameters)
                    {
                        cmd.Parameters.Add(p);
                    }
                }
                pipeline.Commands.Add(cmd);
                var results = pipeline.Invoke();
                pipeline.Dispose();
                runspace.Dispose();
                return results;
            }
            return null;
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.