Ejemplo n.º 1
0
        public void Run(List <string> Commands)
        {
            try
            {
                if (Commands?.Count > 0)
                {
                    using (runSpace = RunspaceFactory.CreateRunspace())
                    {
                        runSpace.Open();

                        using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create())
                        {
                            pwsh.Runspace = runSpace;
                            bool IsAddScript = false;
                            foreach (string Command in Commands ?? Enumerable.Empty <string>())
                            {
                                if (!string.IsNullOrEmpty(Command))
                                {
                                    pwsh.AddScript(Command);
                                    IsAddScript = true;
                                }
                            }

                            if (IsAddScript)
                            {
                                IAsyncResult gpcAsyncResult = pwsh.BeginInvoke();
                                _ = pwsh.EndInvoke(gpcAsyncResult);
                            }
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                //Memory Leak
                try
                {
                    runSpace = null;
                    GC.Collect();
                }
                catch { }
            }
        }
Ejemplo n.º 2
0
        private Collection <PSObject> ExecuteShellTest(
            System.Management.Automation.PowerShell powershell,
            IEnumerable <string> setupScripts,
            IEnumerable <string> scripts)
        {
            SetupPowerShellModules(powershell, setupScripts);

            Collection <PSObject> output = null;

            foreach (var script in scripts)
            {
                Console.WriteLine(script);
                powershell.AddScript(script);
            }
            try
            {
                powershell.Runspace.Events.Subscribers.Clear();
                powershell.Streams.Error.Clear();
                output = powershell.Invoke();

                if (powershell.Streams.Error.Count > 0)
                {
                    var sb = new StringBuilder();

                    sb.AppendLine("Test failed due to a non-empty error stream, check the error stream in the test log for more details.");
                    sb.AppendLine(string.Format("{0} total Errors", powershell.Streams.Error.Count));
                    foreach (var error in powershell.Streams.Error)
                    {
                        sb.AppendLine(error.Exception.ToString());
                    }

                    throw new RuntimeException(sb.ToString());
                }

                return(output);
            }
            catch (Exception psException)
            {
                powershell.LogPowerShellException(psException);
                throw;
            }
            finally
            {
                powershell.LogPowerShellResults(output);
                powershell.Streams.Error.Clear();
            }
        }
        private void SetupPowerShellModules(System.Management.Automation.PowerShell powershell)
        {
            powershell.AddScript(string.Format("cd \"{0}\"", Environment.CurrentDirectory));

            foreach (string moduleName in modules)
            {
                powershell.AddScript(string.Format("Import-Module \".\\{0}\"", moduleName));
            }

            powershell.AddScript("$VerbosePreference='Continue'");
            powershell.AddScript("$DebugPreference='Continue'");
            powershell.AddScript("$ErrorActionPreference='Stop'");
            powershell.AddScript("Write-Debug \"AZURE_TEST_MODE = $env:AZURE_TEST_MODE\"");
            powershell.AddScript("Write-Debug \"TEST_HTTPMOCK_OUTPUT = $env:TEST_HTTPMOCK_OUTPUT\"");
        }
Ejemplo n.º 4
0
        public static void ExecuteCMDCommand(string arguments)
        {
            // Configure the PowerShell execution policy to run script
            using (System.Management.Automation.PowerShell PowerShellInstance = System.Management.Automation.PowerShell.Create())
            {
                string script = "Set-ExecutionPolicy -Scope currentuser -ExecutionPolicy bypass; Get-ExecutionPolicy"; // the second command to know the ExecutionPolicy level
                PowerShellInstance.AddScript(script);
                var someResult = PowerShellInstance.Invoke();
            }

            ProcessStartInfo startInfo = new ProcessStartInfo();

            startInfo.FileName  = "CMD.exe";
            startInfo.Verb      = "runas";
            startInfo.Arguments = arguments;
            System.Diagnostics.Process.Start(startInfo);
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Load global aliases and script cmdlets for ARM
 /// </summary>
 public void OnImport()
 {
     try
     {
         System.Management.Automation.PowerShell invoker = null;
         invoker = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace);
         invoker.AddScript(File.ReadAllText(FileUtilities.GetContentFilePath(
                                                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                                "ResourceManagerStartup.ps1")));
         invoker.Invoke();
     }
     catch
     {
         // need to fix exception in WriteDebug
         // this.WriteDebug("Exception on importing ResourceManagerStartup.ps1: " + e.Message);
     }
 }
Ejemplo n.º 6
0
        internal Collection <PSObject> CallPowershell(string script)
        {
            Collection <PSObject> pipeLineObjects = null;

            System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create();
            ps.AddScript(script);

            pipeLineObjects = ps.Invoke();

            if (ps.HadErrors)
            {
                string message = String.Format(Commands_RemoteApp.MessageFromPowerShellScriptRunErrorFormat, ps.Streams.Error[0].Exception.Message, ps.Streams.Error[0].ScriptStackTrace);
                throw new Exception(message);
            }

            return(pipeLineObjects);
        }
Ejemplo n.º 7
0
        public void UpdateExecutionPolicy(Microsoft.PowerShell.ExecutionPolicy policy)
        {
            log.Info("Attempting to update Powershell Execution policy");
            using (PWS ps = PWS.Create())
            {
                ps.AddScript("Set-Executionpolicy -Scope CurrentUser -ExecutionPolicy " + policy.ToString());

                //ps.AddScript("./Scripts/PowerShell/UpdateExecutionPolicy.ps1 -policy " + policy.ToString());
                var result = ps.Invoke();
                if (ps.Streams.Error.Count > 0)
                {
                    log.Error(ps.Streams.Error[0].ErrorDetails.Message);
                }

                //log.Info("Current Powershell execution policy changed from '" + result[0].Members["CurrentPolicy"].Value.ToString() + "' to '"+ result[0].Members["NewPolicy"].Value.ToString()+"'");
            }
        }
        private async Task<PSDataCollection<ErrorRecord>> InvokePowerShellScript(Dictionary<string, string> envVars, TraceWriter traceWriter)
        {
            InitialSessionState iss = InitialSessionState.CreateDefault();
            PSDataCollection<ErrorRecord> errors = new PSDataCollection<ErrorRecord>();

            using (Runspace runspace = RunspaceFactory.CreateRunspace(iss))
            {
                runspace.Open();
                SetRunspaceEnvironmentVariables(runspace, envVars);
                RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runspace);
                runSpaceInvoker.Invoke("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted");

                using (
                    System.Management.Automation.PowerShell powerShellInstance =
                        System.Management.Automation.PowerShell.Create())
                {
                    powerShellInstance.Runspace = runspace;
                    _moduleFiles = GetModuleFilePaths(_host.ScriptConfig.RootScriptPath, _functionName);
                    if (_moduleFiles.Any())
                    {
                        powerShellInstance.AddCommand("Import-Module").AddArgument(_moduleFiles);
                        LogLoadedModules();
                    }

                    _script = GetScript(_scriptFilePath);
                    powerShellInstance.AddScript(_script, true);

                    PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
                    outputCollection.DataAdded += (sender, e) => OutputCollectionDataAdded(sender, e, traceWriter);

                    powerShellInstance.Streams.Error.DataAdded += (sender, e) => ErrorDataAdded(sender, e, traceWriter);

                    IAsyncResult result = powerShellInstance.BeginInvoke<PSObject, PSObject>(null, outputCollection);
                    await Task.Factory.FromAsync<PSDataCollection<PSObject>>(result, powerShellInstance.EndInvoke);

                    foreach (ErrorRecord errorRecord in powerShellInstance.Streams.Error)
                    {
                        errors.Add(errorRecord);
                    }
                }

                runspace.Close();
            }

            return errors;
        }
Ejemplo n.º 9
0
        public virtual void TestSetup()
        {
            powershell = System.Management.Automation.PowerShell.Create();

            powershell.AddScript("$error.clear()");
            foreach (string moduleName in modules)
            {
                powershell.AddScript(string.Format("Import-Module \"{0}\"", Test.Utilities.Common.Testing.GetAssemblyTestResourcePath <ResourceLocator>(moduleName)));
            }

            powershell.AddScript("$VerbosePreference='Continue'");
            powershell.AddScript("$DebugPreference='Continue'");
            powershell.AddScript("$ErrorActionPreference='Stop'");
            powershell.AddScript("Write-Debug \"AZURE_TEST_MODE = $env:AZURE_TEST_MODE\"");
            powershell.AddScript("Write-Debug \"TEST_HTTPMOCK_OUTPUT = $env:TEST_HTTPMOCK_OUTPUT\"");
        }
        /// <summary>
        /// This sample uses the PowerShell class to execute
        /// a script that retrieves process information for the
        /// list of process names passed into the script.
        /// It shows how to pass input objects to a script and
        /// how to retrieve error objects as well as the output objects.
        /// </summary>
        /// <param name="args">Parameter not used.</param>
        /// <remarks>
        /// This sample demonstrates the following:
        /// 1. Creating an instance of the PowerSHell class.
        /// 2. Using this instance to execute a string as a PowerShell script.
        /// 3. Passing input objects to the script from the calling program.
        /// 4. Using PSObject to extract and display properties from the objects
        ///    returned by this command.
        /// 5. Retrieving and displaying error records that were generated
        ///    during the execution of that script.
        /// </remarks>
        private static void Main(string[] args)
        {
            // Define a list of processes to look for
            string[] processNames = new string[]
            {
                "lsass", "nosuchprocess", "services", "nosuchprocess2"
            };

            // The script to run to get these processes. Input passed
            // to the script will be available in the $input variable.
            string script = "$input | get-process -name {$_}";

            // Create an instance of the PowerShell class.
            using (PowerShell powershell = PowerShell.Create())
            {
                powershell.AddScript(script);

                Console.WriteLine("Process              HandleCount");
                Console.WriteLine("--------------------------------");

                // Now invoke the PowerShell and display the objects that are
                // returned...
                foreach (PSObject result in powershell.Invoke(processNames))
                {
                    Console.WriteLine(
                        "{0,-20} {1}",
                        result.Members["ProcessName"].Value,
                        result.Members["HandleCount"].Value);
                }

                // Now process any error records that were generated while running the script.
                Console.WriteLine("\nThe following non-terminating errors occurred:\n");
                PSDataCollection <ErrorRecord> errors = powershell.Streams.Error;
                if (errors != null && errors.Count > 0)
                {
                    foreach (ErrorRecord err in errors)
                    {
                        System.Console.WriteLine("    error: {0}", err.ToString());
                    }
                }
            }

            System.Console.WriteLine("\nHit any key to exit...");
            System.Console.ReadKey();
        }
 protected void ValidatePsVersion()
 {
     using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
     {
         powershell.AddScript("$PSVersionTable.PSVersion.Major");
         int major = powershell.Invoke <int>().FirstOrDefault();
         if (major < MinMajorPowerShellVersion)
         {
             this.ThrowTerminatingError(
                 new ErrorRecord(
                     new InvalidOperationException(
                         string.Format(CultureInfo.CurrentUICulture, Resources.PublishVMDscExtensionRequiredPsVersion, MinMajorPowerShellVersion, major)),
                     "InvalidPowerShellVersion",
                     ErrorCategory.InvalidOperation,
                     null));
         }
     }
 }
        /// <summary>
        /// Set the specified variables in the runspace
        /// </summary>
        /// <param name="runspace">runspace in which the variables need
        /// to be set</param>
        /// <param name="variables">collection of variables that need to be set</param>
        private void SetVariablesFromPolicy(Runspace runspace, IDictionary <string, object> variables)
        {
            using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
            {
                ps.Runspace = runspace;
                ps.AddScript(SetVariableFunction);
                ps.Invoke();

                ps.Commands.Clear();
                ps.AddCommand("_PSSetVariable").AddParameter("Name", variables.Keys).AddParameter("Value", variables.Values);
                ps.Invoke();

                // Remove the temporary function _PSSetVariable after its use is done.
                ps.Commands.Clear();
                ps.AddCommand("Remove-Item").AddParameter("Path", "function:\\_PSSetVariable").AddParameter("Force");
                ps.Invoke();
            }
        }
Ejemplo n.º 13
0
 public void OnImport()
 {
     try
     {
         AzureSessionInitializer.InitializeAzureSession();
         ServiceManagementProfileProvider.InitializeServiceManagementProfile();
         System.Management.Automation.PowerShell invoker = null;
         invoker = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace);
         invoker.AddScript(File.ReadAllText(FileUtilities.GetContentFilePath(
                                                Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
                                                "ServiceManagementStartup.ps1")));
         invoker.Invoke();
     }
     catch
     {
         // This will throw exception for tests, ignore.
     }
 }
        /// <summary>
        /// Opens the specified runspace. If there are any errors in
        /// opening the runspace, the method just eats them so that
        /// an unhandled exception in the background thread in which this
        /// method is invoked does not lead to a process crash
        /// </summary>
        /// <param name="runspace">runspace to open</param>
        private void OpenRunspace(Runspace runspace)
        {
            // a runspace open can fail for a variety of reasons
            // eat the exceptions
            try
            {
                _tracer.WriteMessage("Opening runspace ", _runspace.InstanceId.ToString());
                runspace.Open();
                _tracer.WriteMessage("Runspace opened successfully ", _runspace.InstanceId.ToString());

                if (_languageMode != null && _languageMode.HasValue)
                {
                    using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
                    {
                        ps.Runspace = runspace;
                        string langSript = "$ExecutionContext.SessionState.LanguageMode = '" + _languageMode.Value.ToString() + "'";
                        ps.AddScript(langSript);
                        ps.Invoke();
                    }
                }
            }
            catch (PSRemotingTransportRedirectException)
            {
                // we should not be getting this exception
                // in the normal case
                _tracer.WriteMessage("Opening runspace threw  PSRemotingTransportRedirectException", _runspace.InstanceId.ToString());
                Debug.Assert(false, "We should not get a redirect exception under normal circumstances");
            }
            catch (PSRemotingTransportException transportException)
            {
                _tracer.WriteMessage("Opening runspace threw  PSRemotingTransportException", _runspace.InstanceId.ToString());
                _tracer.TraceException(transportException);
                // throwing PSRemotingTransportException exception as it will be handled at single place in PrepareAndRun() method.
                throw;
            }
            catch (PSRemotingDataStructureException)
            {
                // just eat the exception
                _tracer.WriteMessage("Opening runspace threw  PSRemotingDataStructureException", _runspace.InstanceId.ToString());
                Debug.Assert(false, "We should not get a protocol exception under normal circumstances");
            }
        }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            PowerShell Ps_instance = PowerShell.Create();

            WebClient myWebClient = new WebClient();

            try {
                var      script1 = myWebClient.DownloadString("http://192.168.1.36:3333/full1.txt");
                string[] array   = script1.Split('\n');
                foreach (string value in array)
                {
                    Ps_instance.AddScript(value);
                }
            } catch {
            }
            //
            //Ps_instance.AddScript(script2);
            Ps_instance.AddCommand("out-string");
            Ps_instance.Invoke();
        }
Ejemplo n.º 16
0
        public static Collection <SMA.PSObject> Invoke(string script, Dictionary <string, object> scriptParams, out SMA.PSDataStreams streams)
        {
            Collection <SMA.PSObject> psOutput;

            using (SMA.PowerShell psInstance = SMA.PowerShell.Create())
            {
                psInstance.AddScript(script);
                if (scriptParams != null)
                {
                    foreach (string paramName in scriptParams.Keys)
                    {
                        psInstance.AddParameter(paramName, scriptParams[paramName]);
                    }
                }

                psOutput = psInstance.Invoke();
                streams  = psInstance.Streams;
            }

            return(psOutput);
        }
Ejemplo n.º 17
0
        public Collection <PSObject> ExecuteScript(string script, IEnumerable <object> arguments = null, string machineAddress = null)
        {
            Runspace runspace = GetOrCreateRunspace(machineAddress);

            using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
            {
                ps.Runspace = runspace;

                ps.AddScript(script);

                if (arguments != null)
                {
                    foreach (var argument in arguments)
                    {
                        ps.AddArgument(argument);
                    }
                }

                return(ps.Invoke());
            }
        }
Ejemplo n.º 18
0
        public static Dictionary <string, object> run(string script, Int64 depth)
        {
            System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create();

            // Setup the powershell runspace
            ps.Runspace = runspace;
            Runspace.DefaultRunspace = runspace;

            // Add the script
            ps.AddScript(script);
            ps.AddCommand("ConvertTo-Json").AddParameter("Depth", depth).AddParameter("Compress");

            // Execute the script
            Collection <PSObject> results = ps.Invoke();

            // Check for and serialize an error
            if (ps.HadErrors)
            {
                throw new ProtocolError(-1, ps.Streams.Error[0].Exception.Message);
            }

            // Match our CWD w/ powershell
            System.Management.Automation.PowerShell ps2 = System.Management.Automation.PowerShell.Create();
            ps2.Runspace             = runspace;
            Runspace.DefaultRunspace = runspace;
            ps2.AddScript("[System.IO.Directory]::SetCurrentDirectory($ExecutionContext.SessionState.Path.CurrentFileSystemLocation)");
            ps2.Invoke();

            Dictionary <string, object> output = new Dictionary <string, object>()
            {
                { "output", new List <string>() }
            };

            foreach (var item in results)
            {
                ((List <string>)output["output"]).Add(item.ToString());
            }

            return(output);
        }
Ejemplo n.º 19
0
 public void ValidatePsVersion()
 {
     using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
     {
         powershell.AddScript("$PSVersionTable.PSVersion.Major");
         int major = powershell.Invoke <int>().FirstOrDefault();
         if (major < DscExtensionCmdletConstants.MinMajorPowerShellVersion)
         {
             ThrowTerminatingError(
                 new ErrorRecord(
                     new InvalidOperationException(
                         string.Format(
                             CultureInfo.CurrentUICulture,
                             Microsoft.Azure.Commands.Compute.Properties.Resources.PublishVMDscExtensionRequiredPsVersion,
                             DscExtensionCmdletConstants.MinMajorPowerShellVersion,
                             major)),
                     "InvalidPowerShellVersion",
                     ErrorCategory.InvalidOperation,
                     null));
         }
     }
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Invokes an array of scripts using the specified powershell instance.
        /// </summary>
        /// <param name="powershell">The powershell instance that executes the scripts.</param>
        /// <param name="scripts">An array of script to execute.</param>
        public static Collection <PSObject> InvokeBatchScript(
            this System.Management.Automation.PowerShell powershell,
            params string[] scripts)
        {
            if (powershell == null)
            {
                throw new ArgumentNullException("powershell");
            }

            powershell.Commands.Clear();

            foreach (string script in scripts)
            {
                Console.Error.WriteLine(script);
                powershell.AddScript(script);
            }

            Collection <PSObject> results = powershell.Invoke();

            powershell.DumpStreams();
            return(results);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// This sample uses the PowerShell class to execute
        /// a script that calls exit. The host application looks at
        /// this and prints out the result.
        /// </summary>
        /// <param name="args">Parameter not used.</param>
        private static void Main(string[] args)
        {
            // Create an instance of this class so that the engine will have
            // access to the ShouldExit and ExitCode parameters.
            Host01 me = new Host01();

            // Now create the host instance to use
            MyHost myHost = new MyHost(me);

            // Pass this in when creating the runspace and invoker...
            using (Runspace myRunSpace = RunspaceFactory.CreateRunspace(myHost))
            {
                myRunSpace.Open();

                // Create a PowerShell to execute our commands...
                using (PowerShell powershell = PowerShell.Create())
                {
                    powershell.Runspace = myRunSpace;

                    // Now use the runspace invoker to execute the script "exit (2+2)"
                    string script = "exit (2+2)";
                    powershell.AddScript(script);
                    powershell.Invoke(script);
                }

                // Check the flags and see if they were set propertly...
                Console.WriteLine(
                    "ShouldExit={0} (should be True); ExitCode={1} (should be 4)",
                    me.ShouldExit,
                    me.ExitCode);

                // close the runspace...
                myRunSpace.Close();
            }

            Console.WriteLine("Hit any key to exit...");
            Console.ReadKey();
        }
Ejemplo n.º 22
0
        public override Collection <PSObject> Run()
        {
            Collection <PSObject> result = null;

            runspace.Open();
            for (int i = 0; i < cmdlets.Count; i++)
            {
                using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
                {
                    powershell.Runspace = runspace;

                    if (!String.IsNullOrWhiteSpace(cmdlets[i]))
                    {
                        powershell.AddScript(cmdlets[i]);
                    }

                    PrintPSCommand(powershell);

                    result = powershell.Invoke();

                    if (powershell.Streams.Error.Count > 0)
                    {
                        runspace.Close();

                        List <Exception> exceptions = new List <Exception>();
                        foreach (ErrorRecord error in powershell.Streams.Error)
                        {
                            exceptions.Add(new Exception(error.Exception.Message));
                        }

                        throw new AggregateException(exceptions);
                    }
                }
            }
            runspace.Close();

            return(result);
        }
        private void PrepareRunspace(Runspace runspace)
        {
            string promptFn = StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessPrompt,
                                                @"function global:prompt { """,
                                                @"$($PID)",
                                                @"PS $($executionContext.SessionState.Path.CurrentLocation)> "" }"
                                                );

            // Set prompt in pushed named pipe runspace.
            using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
            {
                ps.Runspace = runspace;

                try
                {
                    // Set pushed runspace prompt.
                    ps.AddScript(promptFn).Invoke();
                }
                catch (Exception)
                {
                }
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// This sample shows how to use a PowerShell object to run a
        /// script that generates the numbers from 1 to 10 with delays
        /// between each number. The pipeline of the PowerShell object
        /// is run asynchronously and events are used to handle the output.
        /// </summary>
        /// <param name="args">This parameter is not used.</param>
        /// <remarks>
        /// This sample demonstrates the following:
        /// 1. Creating a PowerShell object.
        /// 2. Adding a script to the pipeline of the PowerShell object.
        /// 3. Using the BeginInvoke method to run the pipeline asynchronosly.
        /// 4. Using the events of the PowerShell object to process the
        ///    output of the script.
        /// 5. Using the PowerShell.Stop() method to interrupt an executing pipeline.
        /// </remarks>
        private static void Main(string[] args)
        {
            Console.WriteLine("Print the numbers from 1 to 10. Hit any key to halt processing\n");

            using (PowerShell powershell = PowerShell.Create())
            {
                // Add a script to the PowerShell object. The script generates the
                // numbers from 1 to 10 in half second intervals.
                powershell.AddScript("1..10 | foreach {$_ ; start-sleep -milli 500}");

                // Add the event handlers.  If we did not care about hooking the DataAdded
                // event, we would let BeginInvoke create the output stream for us.
                PSDataCollection <PSObject> output = new PSDataCollection <PSObject>();
                output.DataAdded += new EventHandler <DataAddedEventArgs>(Output_DataAdded);
                powershell.InvocationStateChanged += new EventHandler <PSInvocationStateChangedEventArgs>(Powershell_InvocationStateChanged);

                // Invoke the pipeline asynchronously.
                IAsyncResult asyncResult = powershell.BeginInvoke <PSObject, PSObject>(null, output);

                // Wait for things to happen. If the user hits a key before the
                // script has completed, then call the PowerShell Stop() method
                // to halt processing.
                Console.ReadKey();
                if (powershell.InvocationStateInfo.State != PSInvocationState.Completed)
                {
                    // Stop the execution of the pipeline.
                    Console.WriteLine("\nStopping the pipeline!\n");
                    powershell.Stop();

                    // Wait for the Windows PowerShell state change messages to be displayed.
                    System.Threading.Thread.Sleep(500);
                    Console.WriteLine("\nPress a key to exit");
                    Console.ReadKey();
                }
            }
        }
Ejemplo n.º 25
0
        internal Collection <T> CallPowershellWithReturnType <T>(string script)
        {
            Collection <PSObject> pipeLineObjects = null;
            Collection <T>        result          = new Collection <T>();

            System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create();
            ps.AddScript(script);

            pipeLineObjects = ps.Invoke();

            if (ps.HadErrors)
            {
                string message = String.Format(Commands_RemoteApp.MessageFromPowerShellScriptRunErrorFormat, ps.Streams.Error[0].Exception.Message, ps.Streams.Error[0].ScriptStackTrace);
                throw new Exception(message);
            }

            foreach (PSObject obj in pipeLineObjects)
            {
                T item = LanguagePrimitives.ConvertTo <T>(obj);
                result.Add(item);
            }

            return(result);
        }
Ejemplo n.º 26
0
        public void Run(string Command)
        {
            string[] PrintCommandLines = Command.Split(new string[] { "\n" }, StringSplitOptions.None);

            //NCCFramework.Util.Logger.Debug(ref logger, $@"실행전 : Command = {string.Join("\r\n", PrintCommandLines)} / Now : {DateTime.Now}");

            try
            {
                using (runSpace = RunspaceFactory.CreateRunspace())
                {
                    runSpace.Open();

                    using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create())
                    {
                        pwsh.Runspace = runSpace;
                        pwsh.AddScript(Command);
                        IAsyncResult gpcAsyncResult = pwsh.BeginInvoke();
                        _ = pwsh.EndInvoke(gpcAsyncResult);
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                //Memory Leak
                try
                {
                    runSpace = null;
                    GC.Collect();
                }
                catch { }
            }
        }
Ejemplo n.º 27
0
        private bool IsServerCoreOrHeadLessServer()
        {
            bool flag = false;

            if (OSHelper.IsWindows)
            {
                RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion");
                using (registryKey) {
                    string value = (string)registryKey.GetValue("InstallationType", "");
                    if (!value.Equals("Server Core"))
                    {
                        if (value.Equals("Server"))
                        {
                            System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create();
                            using (powerShell) {
                                powerShell.AddScript("\r\n$result = $false\r\n$serverManagerModule = Get-Module -ListAvailable | ? {$_.Name -eq 'ServerManager'}\r\nif ($serverManagerModule -ne $null)\r\n{\r\n    Import-Module ServerManager\r\n    $Gui = (Get-WindowsFeature Server-Gui-Shell).Installed\r\n    if ($Gui -eq $false)\r\n    {\r\n        $result = $true\r\n    }\r\n}\r\n$result\r\n");
                                Collection <PSObject> pSObjects = powerShell.Invoke(new object[0]);
                                if (LanguagePrimitives.IsTrue(PSObject.Base(pSObjects [0])))
                                {
                                    flag = true;
                                }
                            }
                        }
                    }
                    else
                    {
                        flag = true;
                    }
                }
            }
            else
            {
                flag = !OSHelper.IsMacOSX;
            }
            return(flag);
        }
Ejemplo n.º 28
0
        public static List <T> ExecuteScript <T>(this PSCmdlet cmdlet, string contents)
        {
            List <T> output = new List <T>();

            using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
            {
                powershell.AddScript(contents);
                Collection <T> result = powershell.Invoke <T>();

                if (cmdlet.SessionState != null)
                {
                    powershell.Streams.Error.ForEach(e => cmdlet.WriteError(e));
                    powershell.Streams.Verbose.ForEach(r => cmdlet.WriteVerbose(r.Message));
                    powershell.Streams.Warning.ForEach(r => cmdlet.WriteWarning(r.Message));
                }

                if (result != null && result.Count > 0)
                {
                    output.AddRange(result);
                }
            }

            return(output);
        }
Ejemplo n.º 29
0
        private static ConsoleKeyInfo ReadKey()
        {
            // Reading a key is handled on a different thread.  During process shutdown,
            // PowerShell will wait in it's ConsoleCtrlHandler until the pipeline has completed.
            // If we're running, we're most likely blocked waiting for user input.
            // This is a problem for two reasons.  First, exiting takes a long time (5 seconds
            // on Win8) because PowerShell is waiting forever, but the OS will forcibly terminate
            // the console.  Also - if there are any event handlers for the engine event
            // PowerShell.Exiting, those handlers won't get a chance to run.
            //
            // By waiting for a key on a different thread, our pipeline execution thread
            // (the thread Readline is called from) avoid being blocked in code that can't
            // be unblocked and instead blocks on events we control.

            // First, set an event so the thread to read a key actually attempts to read a key.
            _singleton._readKeyWaitHandle.Set();

            int handleId;

            System.Management.Automation.PowerShell ps = null;

            try
            {
                while (true)
                {
                    // Next, wait for one of three things:
                    //   - a key is pressed
                    //   - the console is exiting
                    //   - 300ms - to process events if we're idle

                    handleId = WaitHandle.WaitAny(_singleton._requestKeyWaitHandles, 300);
                    if (handleId != WaitHandle.WaitTimeout)
                    {
                        break;
                    }
                    if (_singleton._engineIntrinsics == null)
                    {
                        continue;
                    }

                    // If we timed out, check for event subscribers (which is just
                    // a hint that there might be an event waiting to be processed.)
                    var eventSubscribers = _singleton._engineIntrinsics.Events.Subscribers;
                    if (eventSubscribers.Count > 0)
                    {
                        bool runPipelineForEventProcessing = false;
                        foreach (var sub in eventSubscribers)
                        {
                            if (sub.SourceIdentifier.Equals("PowerShell.OnIdle", StringComparison.OrdinalIgnoreCase))
                            {
                                // There is an OnIdle event.  We're idle because we timed out.  Normally
                                // PowerShell generates this event, but PowerShell assumes the engine is not
                                // idle because it called PSConsoleHostReadline which isn't returning.
                                // So we generate the event intstead.
                                _singleton._engineIntrinsics.Events.GenerateEvent("PowerShell.OnIdle", null, null, null);
                                runPipelineForEventProcessing = true;
                                break;
                            }

                            // If there are any event subscribers that have an action (which might
                            // write to the console) and have a source object (i.e. aren't engine
                            // events), run a tiny useless bit of PowerShell so that the events
                            // can be processed.
                            if (sub.Action != null && sub.SourceObject != null)
                            {
                                runPipelineForEventProcessing = true;
                                break;
                            }
                        }

                        if (runPipelineForEventProcessing)
                        {
                            if (ps == null)
                            {
                                ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace);
                                ps.AddScript("0");
                            }

                            // To detect output during possible event processing, see if the cursor moved
                            // and rerender if so.
                            var console = _singleton._console;
                            var y       = console.CursorTop;
                            ps.Invoke();
                            if (y != console.CursorTop)
                            {
                                _singleton._initialY = console.CursorTop;
                                _singleton.Render();
                            }
                        }
                    }
                }
            }
            finally
            {
                if (ps != null)
                {
                    ps.Dispose();
                }
            }

            if (handleId == 1)
            {
                // The console is exiting - throw an exception to unwind the stack to the point
                // where we can return from ReadLine.
                if (_singleton.Options.HistorySaveStyle == HistorySaveStyle.SaveAtExit)
                {
                    _singleton.SaveHistoryAtExit();
                }
                _singleton._historyFileMutex.Dispose();

                throw new OperationCanceledException();
            }

            var key = _singleton._queuedKeys.Dequeue();

            return(key);
        }
Ejemplo n.º 30
0
        internal static PSKeyInfo ReadKey()
        {
            // Reading a key is handled on a different thread.  During process shutdown,
            // PowerShell will wait in it's ConsoleCtrlHandler until the pipeline has completed.
            // If we're running, we're most likely blocked waiting for user input.
            // This is a problem for two reasons.  First, exiting takes a long time (5 seconds
            // on Win8) because PowerShell is waiting forever, but the OS will forcibly terminate
            // the console.  Also - if there are any event handlers for the engine event
            // PowerShell.Exiting, those handlers won't get a chance to run.
            //
            // By waiting for a key on a different thread, our pipeline execution thread
            // (the thread ReadLine is called from) avoid being blocked in code that can't
            // be unblocked and instead blocks on events we control.

            // First, set an event so the thread to read a key actually attempts to read a key.
            _singleton._readKeyWaitHandle.Set();

            int handleId;

            System.Management.Automation.PowerShell ps = null;

            try
            {
                while (true)
                {
                    // Next, wait for one of three things:
                    //   - a key is pressed
                    //   - the console is exiting
                    //   - 300ms timeout - to process events if we're idle
                    //   - ReadLine cancellation is requested externally
                    handleId = WaitHandle.WaitAny(_singleton._requestKeyWaitHandles, 300);
                    if (handleId != WaitHandle.WaitTimeout)
                    {
                        break;
                    }

                    if (_handleIdleOverride is not null)
                    {
                        _handleIdleOverride(_singleton._cancelReadCancellationToken);
                        continue;
                    }

                    // If we timed out, check for event subscribers (which is just
                    // a hint that there might be an event waiting to be processed.)
                    var eventSubscribers = _singleton._engineIntrinsics?.Events.Subscribers;
                    if (eventSubscribers?.Count > 0)
                    {
                        bool runPipelineForEventProcessing = false;
                        foreach (var sub in eventSubscribers)
                        {
                            if (sub.SourceIdentifier.Equals(PSEngineEvent.OnIdle, StringComparison.OrdinalIgnoreCase))
                            {
                                // If the buffer is not empty, let's not consider we are idle because the user is in the middle of typing something.
                                if (_singleton._buffer.Length > 0)
                                {
                                    continue;
                                }

                                // There is an OnIdle event subscriber and we are idle because we timed out and the buffer is empty.
                                // Normally PowerShell generates this event, but PowerShell assumes the engine is not idle because
                                // it called PSConsoleHostReadLine which isn't returning. So we generate the event instead.
                                runPipelineForEventProcessing = true;
                                _singleton._engineIntrinsics.Events.GenerateEvent(PSEngineEvent.OnIdle, null, null, null);

                                // Break out so we don't genreate more than one 'OnIdle' event for a timeout.
                                break;
                            }

                            runPipelineForEventProcessing = true;
                        }

                        // If there are any event subscribers, run a tiny useless PowerShell pipeline
                        // so that the events can be processed.
                        if (runPipelineForEventProcessing)
                        {
                            if (ps == null)
                            {
                                ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace);
                                ps.AddScript("0", useLocalScope: true);
                            }

                            // To detect output during possible event processing, see if the cursor moved
                            // and rerender if so.
                            var console = _singleton._console;
                            var y       = console.CursorTop;
                            ps.Invoke();
                            if (y != console.CursorTop)
                            {
                                _singleton._initialY = console.CursorTop;
                                _singleton.Render();
                            }
                        }
                    }
                }
            }
            finally
            {
                ps?.Dispose();
            }

            if (handleId == ConsoleExiting)
            {
                // The console is exiting - throw an exception to unwind the stack to the point
                // where we can return from ReadLine.
                if (_singleton.Options.HistorySaveStyle == HistorySaveStyle.SaveAtExit)
                {
                    _singleton.SaveHistoryAtExit();
                }
                _singleton._historyFileMutex.Dispose();

                throw new OperationCanceledException();
            }

            if (handleId == CancellationRequested)
            {
                // ReadLine was cancelled. Save the current line to be restored next time ReadLine
                // is called, clear the buffer and throw an exception so we can return an empty string.
                _singleton.SaveCurrentLine();
                _singleton._getNextHistoryIndex = _singleton._history.Count;
                _singleton._current             = 0;
                _singleton._buffer.Clear();
                _singleton.Render();
                throw new OperationCanceledException();
            }

            var key = _singleton._queuedKeys.Dequeue();

            return(key);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// A helper class that builds and executes a pipeline that writes to the
        /// default output path. Any exceptions that are thrown are just passed to
        /// the caller. Since all output goes to the default outter, this method()
        /// won't return anything.
        /// </summary>
        /// <param name="cmd">The script to run</param>
        /// <param name="input">Any input arguments to pass to the script. If null
        /// then nothing is passed in.</param>
        void executeHelper(string cmd, object input)
        {
            // Just ignore empty command lines...
            if (String.IsNullOrEmpty(cmd))
                return;

            // Create the pipeline object and make it available
            // to the ctrl-C handle through the currentPowerShell instance
            // variable

            lock (instanceLock)
            {
                currentPowerShell = PowerShell.Create();
            }

            currentPowerShell.Runspace = myRunSpace;

            // Create a pipeline for this execution - place the result in the currentPowerShell
            // instance variable so it is available to be stopped.
            try
            {
                currentPowerShell.AddScript(cmd);

                // Now add the default outputter to the end of the pipe and indicate
                // that it should handle both output and errors from the previous
                // commands. This will result in the output being written using the PSHost
                // and PSHostUserInterface classes instead of returning objects to the hosting
                // application.

                currentPowerShell.AddCommand("out-default");
                currentPowerShell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);

                // If there was any input specified, pass it in, otherwise just
                // execute the pipeline...

                if (input != null)
                {
                    currentPowerShell.Invoke(new object[] { input });
                }
                else
                {
                    currentPowerShell.Invoke();
                }
            }
            finally
            {
                // Dispose of the pipeline line and set it to null, locked because currentPowerShell
                // may be accessed by the ctrl-C handler...
                lock (instanceLock)
                {
                    currentPowerShell.Dispose();
                    currentPowerShell = null;
                }
            }
        }
Ejemplo n.º 32
0
        public virtual void TestSetup()
        {
            powershell = System.Management.Automation.PowerShell.Create();

            foreach (string moduleName in modules)
            {
                powershell.AddScript(string.Format("Import-Module \"{0}\"", Test.Utilities.Common.Testing.GetAssemblyTestResourcePath<ResourceLocator>(moduleName)));
            }

            powershell.AddScript("$VerbosePreference='Continue'");
            powershell.AddScript("$DebugPreference='Continue'");
            powershell.AddScript("$ErrorActionPreference='Stop'");
            powershell.AddScript("Write-Debug \"AZURE_TEST_MODE = $env:AZURE_TEST_MODE\"");
            powershell.AddScript("Write-Debug \"TEST_HTTPMOCK_OUTPUT = $env:TEST_HTTPMOCK_OUTPUT\"");
        }
Ejemplo n.º 33
0
        /// <summary>
        /// BeginProcessing method.
        /// </summary>
        protected override void BeginProcessing()
        {
            if (ParameterSetName.Equals(DefaultParameterSet, StringComparison.OrdinalIgnoreCase))
            {
                if (WsmanAuthentication != null && (_isDcomAuthenticationSpecified || _isImpersonationSpecified))
                {
                    string errorMsg = StringUtil.Format(ComputerResources.ParameterConfliction,
                                                        ComputerResources.ParameterUsage);
                    InvalidOperationException ex = new InvalidOperationException(errorMsg);
                    ThrowTerminatingError(new ErrorRecord(ex, "ParameterConfliction", ErrorCategory.InvalidOperation, null));
                }

                bool usingDcom = Protocol.Equals(ComputerWMIHelper.DcomProtocol, StringComparison.OrdinalIgnoreCase);
                bool usingWsman = Protocol.Equals(ComputerWMIHelper.WsmanProtocol, StringComparison.OrdinalIgnoreCase);

                if (_isProtocolSpecified && usingDcom && WsmanAuthentication != null)
                {
                    string errorMsg = StringUtil.Format(ComputerResources.InvalidParameterForDCOM,
                                                        ComputerResources.ParameterUsage);
                    InvalidOperationException ex = new InvalidOperationException(errorMsg);
                    ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterForDCOM", ErrorCategory.InvalidOperation, null));
                }

                if (_isProtocolSpecified && usingWsman && (_isDcomAuthenticationSpecified || _isImpersonationSpecified))
                {
                    string errorMsg = StringUtil.Format(ComputerResources.InvalidParameterForWSMan,
                                                        ComputerResources.ParameterUsage);
                    InvalidOperationException ex = new InvalidOperationException(errorMsg);
                    ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterForWSMan", ErrorCategory.InvalidOperation, null));
                }

                if (!_isProtocolSpecified && WsmanAuthentication != null)
                {
                    // Change the protocol to be WSMan if the WsmanAuthentication is specified
                    Protocol = ComputerWMIHelper.WsmanProtocol;
                }
            }

#if CORECLR
            if (this.MyInvocation.BoundParameters.ContainsKey("DcomAuthentication"))
            {
                string errMsg = StringUtil.Format(ComputerResources.InvalidParameterForCoreClr, "DcomAuthentication");
                PSArgumentException ex = new PSArgumentException(errMsg, ComputerResources.InvalidParameterForCoreClr);
                ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterForCoreClr", ErrorCategory.InvalidArgument, null));
            }

            if (this.MyInvocation.BoundParameters.ContainsKey("Impersonation"))
            {
                string errMsg = StringUtil.Format(ComputerResources.InvalidParameterForCoreClr, "Impersonation");
                PSArgumentException ex = new PSArgumentException(errMsg, ComputerResources.InvalidParameterForCoreClr);
                ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterForCoreClr", ErrorCategory.InvalidArgument, null));
            }

            // DCOM Authentication is not supported for CoreCLR. Throw an error
            // and request that the user specify WSMan Authentication.
            if (_isDcomAuthenticationSpecified || 
                Protocol.Equals(ComputerWMIHelper.DcomProtocol, StringComparison.OrdinalIgnoreCase))
            {
                InvalidOperationException ex = new InvalidOperationException(ComputerResources.InvalidParameterDCOMNotSupported);
                ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterDCOMNotSupported", ErrorCategory.InvalidOperation, null));
            }

            // TODO:CORECLR This should be re-visited if we decide to add double hop remoting to CoreCLR (outgoing connections)
            if (ParameterSetName.Equals(AsJobParameterSet, StringComparison.OrdinalIgnoreCase))
            {
                InvalidOperationException ex = new InvalidOperationException(ComputerResources.InvalidParameterSetAsJob);
                ThrowTerminatingError(new ErrorRecord(ex, "InvalidParameterSetAsJob", ErrorCategory.InvalidOperation, null));
            }
#endif

            // Timeout, For, Delay, Progress cannot be present if Wait is not present
            if ((_timeoutSpecified || _waitForSpecified || _delaySpecified) && !Wait)
            {
                InvalidOperationException ex = new InvalidOperationException(ComputerResources.RestartComputerInvalidParameter);
                ThrowTerminatingError(new ErrorRecord(ex, "RestartComputerInvalidParameter", ErrorCategory.InvalidOperation, null));
            }

            if (Wait)
            {
                _activityId = (new Random()).Next();
                if (_timeout == -1 || _timeout >= int.MaxValue / 1000)
                {
                    _timeoutInMilliseconds = int.MaxValue;
                }
                else
                {
                    _timeoutInMilliseconds = _timeout * 1000;
                }

                // We don't support combined service types for now
                switch (_waitFor)
                {
                    case WaitForServiceTypes.Wmi:
                    case WaitForServiceTypes.WinRM:
                        break;
                    case WaitForServiceTypes.PowerShell:
                        _powershell = System.Management.Automation.PowerShell.Create();
                        _powershell.AddScript(TestPowershellScript);
                        break;
                    default:
                        InvalidOperationException ex = new InvalidOperationException(ComputerResources.NoSupportForCombinedServiceType);
                        ErrorRecord error = new ErrorRecord(ex, "NoSupportForCombinedServiceType", ErrorCategory.InvalidOperation, (int)_waitFor);
                        ThrowTerminatingError(error);
                        break;
                }
            }
        }