Пример #1
0
        public override async Task InitializeAsync()
        {
            using var client = new HttpClient();
            var script = await client.GetStringAsync("https://chocolatey.org/install.ps1");

            var initialSessionState = InitialSessionState.CreateDefault();

            initialSessionState.ExecutionPolicy = ExecutionPolicy.Unrestricted;

            using var powershell = PowerShell.Create(initialSessionState);
            powershell.AddScript(script);
            await powershell.InvokeAsync();

            if (operatingSystemProvider is WindowsOperatingSystemProvider windowsOperatingSystemProvider)
            {
                windowsOperatingSystemProvider.UpdatePathEnvironmentVariable();
            }
        }
Пример #2
0
        internal RestService(string serviceName, List <string> urls, List <RestCommand> commands, IEnumerable <string> modules)
            : base(serviceName, typeof(DynamicPowershell).Assembly)
        {
            // we have to give it at least one assembly, even if there isn't any services in it.
            // so I'm giving it a really small assembly

            _serviceName    = serviceName;
            _activeCommands = commands;
            _listenOnUrls   = urls;
            ReverseLookup.Clear();

            var ss = InitialSessionState.CreateDefault();

            ss.ImportPSModule(modules.ToArray());

            RunspacePool = RunspaceFactory.CreateRunspacePool(ss);
            RunspacePool.Open();
        }
Пример #3
0
        protected virtual Runspace OpenRunspace()
        {
            Log.WriteStart("OpenRunspace");

            if (session == null)
            {
                session = InitialSessionState.CreateDefault();
                session.ImportPSModule(new string[] { "FileServerResourceManager" });
            }
            Runspace runSpace = RunspaceFactory.CreateRunspace(session);

            //
            runSpace.Open();
            //
            runSpace.SessionStateProxy.SetVariable("ConfirmPreference", "none");
            Log.WriteEnd("OpenRunspace");
            return(runSpace);
        }
        private Runspace InitializeRunspace(string directory = "ConvertToSARIFModule")
        {
            InitialSessionState initialSessionState = InitialSessionState.CreateDefault();

            // The command will fail for linux and macOS
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                initialSessionState.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;
            }

            var fullPath = Path.GetFullPath($"{directory}/ConvertToSARIF.dll");

            initialSessionState.ImportPSModule(fullPath);

            Runspace runspace = RunspaceFactory.CreateRunspace(initialSessionState);

            return(runspace);
        }
        protected override void EndProcessing()
        {
            var initialSessionState = InitialSessionState.CreateDefault();

            if (Variable != null)
            {
                foreach (var variable in Variable)
                {
                    var value = SessionState.PSVariable.GetValue(variable);
                    initialSessionState.Variables.Add(new SessionStateVariableEntry(variable, value, string.Empty));
                }
            }

            if (Module != null)
            {
                var resolvedModules = new List <string>();
                foreach (var module in Module)
                {
                    if (Path.IsPathRooted(module))
                    {
                        resolvedModules.Add(module);
                    }
                    else
                    {
                        var resolvedPath = Path.Combine(MyInvocation.PSScriptRoot, module);
                        resolvedModules.Add(resolvedPath);
                    }
                }

                initialSessionState.ImportPSModule(resolvedModules.ToArray());
            }

            if (Function != null)
            {
                foreach (var function in Function)
                {
                    var functionInfo = SessionState.InvokeCommand.GetCommand(function, CommandTypes.Function);

                    initialSessionState.Commands.Add(new SessionStateFunctionEntry(function, functionInfo.Definition));
                }
            }

            WriteObject(initialSessionState);
        }
Пример #6
0
        private static Tuple <RunspaceDispatcher, NuGetPSHost> CreateRunspace(IConsole console, string hostName)
        {
            DTE dte = ServiceLocator.GetInstance <DTE>();

            InitialSessionState initialSessionState = InitialSessionState.CreateDefault();

            initialSessionState.Variables.Add(
                new SessionStateVariableEntry(
                    "DTE",
                    (DTE2)dte,
                    "Visual Studio DTE automation object",
                    ScopedItemOptions.AllScope | ScopedItemOptions.Constant)
                );

            // this is used by the functional tests
            var sourceRepositoryProvider = ServiceLocator.GetInstance <ISourceRepositoryProvider>();
            var solutionManager          = ServiceLocator.GetInstance <ISolutionManager>();
            var settings             = ServiceLocator.GetInstance <ISettings>();
            var sourceRepoTuple      = Tuple.Create <string, object>("SourceRepositoryProvider", sourceRepositoryProvider);
            var solutionManagerTuple = Tuple.Create <string, object>("VsSolutionManager", solutionManager);

            Tuple <string, object>[] privateData = new Tuple <string, object>[] { sourceRepoTuple, solutionManagerTuple };

            var host = new NuGetPSHost(hostName, privateData)
            {
                ActiveConsole = console
            };

            var runspace = RunspaceFactory.CreateRunspace(host, initialSessionState);

            runspace.ThreadOptions = PSThreadOptions.Default;
            runspace.Open();

            //
            // Set this runspace as DefaultRunspace so I can script DTE events.
            //
            // WARNING: MSDN says this is unsafe. The runspace must not be shared across
            // threads. I need this to be able to use ScriptBlock for DTE events. The
            // ScriptBlock event handlers execute on DefaultRunspace.
            //
            Runspace.DefaultRunspace = runspace;

            return(Tuple.Create(new RunspaceDispatcher(runspace), host));
        }
        private Runspace CreateRunspace()
        {
            var assemblyBasePath = Path.GetDirectoryName(this.GetType().GetTypeInfo().Assembly.Location);

#if DEBUG
            var tempPath = Path.Combine(assemblyBasePath, "UniversalDashboard.psd1");
#else
            var tempPath = Path.Combine(assemblyBasePath, "..\\UniversalDashboard.psd1");
#endif
            var initialSessionState = InitialSessionState.CreateDefault();
            initialSessionState.Variables.Add(new SessionStateVariableEntry("DashboardService", _dashboardService, "DashboardService", ScopedItemOptions.ReadOnly));

            var runspace = RunspaceFactory.CreateRunspace(new UDHost(), initialSessionState);
            runspace.Open();

            using (var powerShell = PowerShell.Create())
            {
                powerShell.Runspace = runspace;

                Log.Debug($"Loading UD module from {tempPath}");
                powerShell.AddStatement().AddCommand("Import-Module").AddParameter("Name", tempPath);

                powerShell.Invoke();
            }

            if (_initializationScript != null)
            {
                using (var powerShell = PowerShell.Create()) {
                    powerShell.Runspace = runspace;

                    try
                    {
                        SetVariables(powerShell, _initializationScript.Variables);
                        powerShell.AddStatement().AddScript(_initializationScript.ScriptBlock.ToString());
                        powerShell.Invoke();
                    }
                    catch (Exception ex) {
                        Log.Error(ex, "Error running endpoint initialization script.");
                    }
                }
            }

            return(runspace);
        }
Пример #8
0
        public void Run(string name, Dictionary <string, string> psParams)
        {
            // Executionpolicy Bypass - Thanks to @ducke
            //
            InitialSessionState initial = InitialSessionState.CreateDefault();

            // Replace PSAuthorizationManager with a null manager
            // which ignores execution policy
            initial.AuthorizationManager = new AuthorizationManager("Microsoft.PowerShell");

            //Create Runspace
            using (var runspace = RunspaceFactory.CreateRunspace(initial))
            {
                runspace.Open();

                //Create Pipeline
                using (Pipeline pipeline = runspace.CreatePipeline())
                {
                    //TODO: Testing - Please REMOVE!
                    var command = new Command(_scriptIO.FileLocation(name));

                    if (psParams != null)
                    {
                        //TODO: DoEs This Need Item Key or Will Params Run in Order?
                        foreach (var item in psParams)
                        {
                            command.Parameters.Add(null, item.Value);
                        }
                    }

                    pipeline.Commands.Add(command);

                    //Pass in the Scripts text
                    //pipeline.Commands.AddScript(scriptContents); //Previous Way - would allow for script storage in DB
                    pipeline.Commands.Add("Out-String");

                    //Invoke and Save Results
                    var results = pipeline.Invoke();
                    SaveResults(name, results);

                    runspace.Close();
                }
            }
        }
Пример #9
0
        /// <summary>
        /// Creates a Powershell cmdlet with parameters
        /// </summary>
        /// <param name="cmdletName">Name of the cmdlet to invoke</param>
        /// <param name="cmdletType">Class type of the cmdlet to invoke</param>
        /// <param name="parameters">Parameters to pass to the cmdlet</param>
        /// <returns></returns>
        public PowerShell CreatePowershellcmdlet(string cmdletName, Type cmdletType, List <OctoposhCli.CmdletParameter> parameters)
        {
            var initialsessionState =
                InitialSessionState.CreateDefault();

            initialsessionState.Commands.Add(
                new SessionStateCmdletEntry(
                    cmdletName, cmdletType, null)
                );

            var runspace = RunspaceFactory.CreateRunspace(initialsessionState);

            runspace.Open();

            var powershell = PowerShell.Create();

            powershell.Runspace = runspace;

            var command = new Command(cmdletName);

            foreach (var parameter in parameters)
            {
                if (parameter.MultipleValue != null)
                {
                    command.Parameters.Add(new CommandParameter(parameter.Name, parameter.MultipleValue));
                }
                else if (parameter.SingleValue != null)
                {
                    command.Parameters.Add(new CommandParameter(parameter.Name, parameter.SingleValue));
                }
                else if (parameter.Resource != null)
                {
                    command.Parameters.Add(new CommandParameter(parameter.Name, parameter.Resource));
                }
                else
                {
                    command.Parameters.Add(new CommandParameter(parameter.Name));
                }
            }

            powershell.Commands.AddCommand(command);

            return(powershell);
        }
Пример #10
0
        public PowershellManager(string workingDirectory, List <ActionLogItem> actionLogs)
        {
            this.ActionLogs = actionLogs;

            InitialSessionState initial = InitialSessionState.CreateDefault();

            initial.ImportPSModule(new string[] { "ACMESharp" });
            Runspace runspace = RunspaceFactory.CreateRunspace(initial);

            runspace.Open();

            ps          = PowerShell.Create();
            ps.Runspace = runspace;

            if (System.IO.Directory.Exists(workingDirectory))
            {
                SetWorkingDirectory(workingDirectory);
            }
        }
Пример #11
0
        public async Task <object> CreateRunspacePool(object input)
        {
            var inputDict = input as IDictionary <string, object>;

            if (inputDict == null)
            {
                throw new ArgumentException("input");
            }

            var runspaceKey   = (string)inputDict["RunspaceKey"];
            var startupScript = (string)inputDict["StartupScript"];

            if (runspacePools.ContainsKey(runspaceKey))
            {
                throw new InvalidOperationException("Runspace already created with key" + runspaceKey);
            }

            if (string.IsNullOrEmpty(startupScript))
            {
                // Assign a dummy script if not provided.
                startupScript = "Out-Null";
            }

            var initialState = InitialSessionState.CreateDefault();

            var          promptHandler = (Func <object, Task <object> >)inputDict["PromptHandler"];
            PSEdgeRawUI  rawUI         = new PSEdgeRawUI();
            PSEdgeHostUI hostUI        = new PSEdgeHostUI(rawUI, promptHandler);

            PSEdgeHost host = new PSEdgeHost(hostUI);

            // inject the startup script in the runspace so it is invoked automatically.
            initialState.Variables.Add(
                new SessionStateVariableEntry("orbPrivate_RunspaceStartupScript", startupScript, "", ScopedItemOptions.AllScope));

            var runspace = RunspaceFactory.CreateRunspacePool(MinRunspacesPerKey, MaxRunspacesPerKey, initialState, host);

            await Task.Factory.FromAsync(runspace.BeginOpen, runspace.EndOpen, null);

            runspacePools[runspaceKey] = runspace;

            return(true);
        }
        public static async Task <string> ExecuteCommandAsync(string command, string host)
        {
            var initial = InitialSessionState.CreateDefault();

            using var runSpace = RunspaceFactory.CreateRunspace(initial);
            runSpace.Open();

            var scriptBlock = ScriptBlock.Create(command);

            using var results = await PowerShell.Create(runSpace)
                                .AddCommand("Invoke-Command")
                                .AddParameter("ComputerName", host)
                                .AddParameter("ScriptBlock", scriptBlock)
                                .InvokeAsync();

            runSpace.Close();

            return(JsonConvert.SerializeObject(results));
        }
Пример #13
0
        protected void OpenRunspace()
        {
            HostedSolutionLog.LogStart("OpenRunspace");

            if (session == null)
            {
                session = InitialSessionState.CreateDefault();
                session.ImportPSModule(new[] { "virtualmachinemanager" });
            }

            Runspace runSpace = RunspaceFactory.CreateRunspace(session);

            runSpace.Open();
            runSpace.SessionStateProxy.SetVariable("ConfirmPreference", "none");

            RunSpace = runSpace;

            HostedSolutionLog.LogEnd("OpenRunspace");
        }
        /// <summary>
        /// This sample uses an initial session state to create a runspace.
        /// The sample invokes a command from binary module that is loaded by the
        /// initial session state.
        /// </summary>
        /// <param name="args">Parameter not used.</param>
        /// <remarks>
        /// This sample assumes that user has the GetProcessSample02.dll that is
        /// produced by the GetProcessSample02 sample copied to the current directory.
        /// This sample demonstrates the following:
        /// 1. Creating a default initial session state.
        /// 2. Creating a runspace using the initial session state.
        /// 3. Creating a PowerShell object that uses the runspace.
        /// 4. Adding the get-proc cmdlet to the PowerShell object from a
        ///    module.
        /// 5. Using PSObject objects to extract and display properties from
        ///    the objects returned by the cmdlet.
        /// </remarks>
        private static void Main(string[] args)
        {
            // Create an initial session state.
            InitialSessionState iss = InitialSessionState.CreateDefault();

            iss.ImportPSModule(new string[] { @".\GetProcessSample02.dll" });

            // Create a runspace. Notice that no PSHost object is supplied to the
            // CreateRunspace method so the default host is used. See the Host
            // samples for more information on creating your own custom host.
            using (Runspace myRunSpace = RunspaceFactory.CreateRunspace(iss))
            {
                myRunSpace.Open();

                // Create a PowerShell object.
                using (PowerShell powershell = PowerShell.Create())
                {
                    // Add the cmdlet and specify the runspace.
                    powershell.AddCommand(@"GetProcessSample02\get-proc");
                    powershell.Runspace = myRunSpace;

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

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

                    // Display the results.
                    foreach (PSObject result in results)
                    {
                        Console.WriteLine(
                            "{0,-20} {1}",
                            result.Members["ProcessName"].Value,
                            result.Members["HandleCount"].Value);
                    }
                }

                // Close the runspace to release any resources.
                myRunSpace.Close();
            }

            System.Console.WriteLine("Hit any key to exit...");
            System.Console.ReadKey();
        }
Пример #15
0
        private Runspace CreateRunspace()
        {
            var initial = InitialSessionState.CreateDefault();

            initial.ExecutionPolicy = ExecutionPolicy.Unrestricted;

            if (_runnerConfiguration.IsRemote)
            {
                var connectionInfo = new WSManConnectionInfo
                {
                    ComputerName            = _runnerConfiguration.RemoteHostName,
                    AuthenticationMechanism = AuthenticationMechanism.Negotiate
                };

                return(RunspaceFactory.CreateRunspace(connectionInfo));
            }

            return(RunspaceFactory.CreateRunspace(initial));
        }
Пример #16
0
        private static Tuple <Runspace, DagentPSHost> CreateRunspace(IConsole console, string hostName)
        {
            var initialSessionState = InitialSessionState.CreateDefault();
            var privateData         = new Tuple <string, object>[] { };
            var host = new DagentPSHost(hostName, privateData)
            {
                ActiveConsole = console
            };
            var runspace = RunspaceFactory.CreateRunspace(host, initialSessionState);

            runspace.ThreadOptions = PSThreadOptions.Default;
            runspace.Open();
            //
            // Set this runspace as DefaultRunspace so I can script DTE events.
            // WARNING: MSDN says this is unsafe. The runspace must not be shared across threads. I need this to be able to use ScriptBlock for DTE events. The ScriptBlock event handlers execute on DefaultRunspace.
            //
            Runspace.DefaultRunspace = runspace;
            return(Tuple.Create(runspace, host));
        }
Пример #17
0
        private static InitialSessionState CreateInitialSessionState()
        {
            var state = InitialSessionState.CreateDefault();

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                state.ExecutionPolicy = ExecutionPolicy.RemoteSigned;
            }

            state.Variables.Add(new SessionStateVariableEntry(
                                    "ErrorActionPreference", "Stop", description: null
                                    ));

            state.ImportPSModule(
                Path.Combine(TestPath, "PSql.psd1")
                );

            return(state);
        }
Пример #18
0
        private string RunScript()
        {
            // Create a default initial session state and set the execution policy.
            InitialSessionState initialSessionState = InitialSessionState.CreateDefault();

            initialSessionState.ExecutionPolicy = ExecutionPolicy.Unrestricted;

            // Create a runspace and open it. This example uses C#8 simplified using statements
            using Runspace runspace = RunspaceFactory.CreateRunspace(initialSessionState);

            runspace.Open();

            string outputString = "";

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

                string scriptPath = Environment.GetEnvironmentVariable("ScriptPath");
                // specify the script code to run.
                ps.AddScript(scriptPath);

                // execute the script and await the result.
                var output = ps.Invoke();

                // print the resulting pipeline objects to the console.


                foreach (var item in output)
                {
                    Console.WriteLine(item.ToString());
                    outputString += item.ToString() + "\n";
                }
            }
            runspace.Close();

            string responseMessage = string.IsNullOrEmpty(outputString)
                ? $"NO OUTPUT in {Environment.GetEnvironmentVariable("ScriptPath")}"
                : $"Connect to {Environment.GetEnvironmentVariable("ScriptPath")} with OUTPUT: \n\n{outputString}";

            return(responseMessage);
        }
Пример #19
0
        public static async Task <ConsoleOutput> ConvertToGif(this GifOptions model)
        {
            try
            {
                InitialSessionState iss = InitialSessionState.CreateDefault();
                // iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;

                using (Runspace rs = RunspaceFactory.CreateRunspace(iss))
                {
                    rs.Open();

                    var     script    = await(".Scripts.Create-Gif.ps1").GetTextFromEmbeddedResource();
                    Command createGif = new Command(script, true);
                    createGif.Parameters.Add("exec", model.exec);
                    createGif.Parameters.Add("origin", model.origin);
                    createGif.Parameters.Add("destination", model.destination);
                    createGif.Parameters.Add("fps", model.fps);
                    createGif.Parameters.Add("scale", model.scale);
                    createGif.Parameters.Add("flags", model.flags);
                    createGif.Parameters.Add("log", model.log);

                    using (PowerShell ps = PowerShell.Create())
                    {
                        ps.Runspace = rs;
                        ps.Commands.AddCommand(createGif);
                        ps.Invoke();
                        var output = await ps.GetPowershellOutput();

                        if (!output.hasError)
                        {
                            output.result = $"{model.destination} successfully created";
                        }

                        return(output);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.GetExceptionMessageChain());
            }
        }
Пример #20
0
 public bool CreatePsPipeline()
 {
     _startTime           = DateTime.MinValue;
     _endTime             = DateTime.MinValue;
     _taskCompleted       = false;
     _taskStatus          = Status.NOTSTARTED;
     _resultDataTable     = null;
     _resultStringBuilder = new StringBuilder();
     try
     {
         InitialSessionState iss = InitialSessionState.CreateDefault();
         foreach (var v in _variables)
         {
             SessionStateVariableEntry variable = new SessionStateVariableEntry(v.Key, v.Value, null);
             iss.Variables.Add(variable);
         }
         _runspace = RunspaceFactory.CreateRunspace(initialSessionState: iss);
     }
     catch
     {
         _taskCompleted = true;
         _taskStatus    = Status.FAILED;
         throw;
     }
     try
     {
         _runspace.Open();
         _pipeline = _runspace.CreatePipeline();
         foreach (var scriptFile in _scriptFiles)
         {
             string scriptContent = System.IO.File.ReadAllText(scriptFile);
             _pipeline.Commands.AddScript(scriptContent);
         }
         _pipeline.Commands.AddScript(_scriptText);
     }
     catch
     {
         _taskStatus = Status.FAILED;
         throw;
     }
     return(true);
 }
Пример #21
0
        private static string ExecutePowershell(string args)
        {
            InitialSessionState iss = InitialSessionState.CreateDefault();
            Runspace            rs  = RunspaceFactory.CreateRunspace(iss);

            rs.Open();
            PowerShell ps = PowerShell.Create(rs);

            ps.AddCommand("Get-Command");
            Collection <PSObject> results = ps.Invoke();

            StringBuilder stringBuilder = new StringBuilder();

            foreach (PSObject pSObject in results)
            {
                stringBuilder.AppendLine(pSObject.ToString());
            }

            return(stringBuilder.ToString());
        }
Пример #22
0
        public void RegisterMetrics(ICollectorRegistry registry)
        {
            _registry = registry;

            var iss = InitialSessionState.CreateDefault();

            iss.ImportPSModule(new[] { _metricsPowerShellModulePath });
            iss.Types.Add(new SessionStateTypeEntry(new TypeData(typeof(Metric)), false));

            _rs = RunspaceFactory.CreateRunspace(iss);

            // NB if this errors out with something alike:
            //      runspace cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies
            //    you need to change the PowerShell (64-bit and 32-bit) execution policies with:
            //      PowerShell.exe -Command Set-ExecutionPolicy Unrestricted
            //      c:\windows\syswow64\WindowsPowerShell\v1.0\PowerShell.exe -Command Set-ExecutionPolicy Unrestricted
            _rs.Open();

            Log.Information("PowerShell v{PowerShellVersion}", _rs.Version);
        }
Пример #23
0
        public Invoke_XdtTransformSteps()
        {
            var state = InitialSessionState.CreateDefault();

            state.Commands.Add(
                new SessionStateCmdletEntry(
                    "Invoke-XdtTransform",
                    typeof(InvokeXdtTransformCommand),
                    null));


            this._Runspace = RunspaceFactory.CreateRunspace();
            this._Runspace.Open();

            this._Shell          = PowerShell.Create(state);
            this._Shell.Runspace = this._Runspace;

            this._Command = new Command("Invoke-XdtTransform");
            this._Shell.Commands.AddCommand(this._Command);
        }
Пример #24
0
        public PowerShellKernel()
        {
            //Sets the distribution channel to "PSES" so starts can be distinguished in PS7+ telemetry
            Environment.SetEnvironmentVariable("POWERSHELL_DISTRIBUTION_CHANNEL", "dotnet-interactive-powershell");

            var runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault());

            runspace.Open();
            _pwsh = PowerShell.Create(runspace);
            _cancellationSource = new CancellationTokenSource();
            Name = DefaultKernelName;

            // Add Modules directory that contains the helper modules
            string psModulePath = Environment.GetEnvironmentVariable("PSModulePath");

            Environment.SetEnvironmentVariable("PSModulePath",
                                               psModulePath + Path.PathSeparator + Path.Join(
                                                   Path.GetDirectoryName(typeof(PowerShellKernel).Assembly.Location),
                                                   "Modules"));
        }
Пример #25
0
        public PowershellEnvironment(params PowershellModule[] modules)
        {
            if (modules == null)
            {
                runspace = RunspaceFactory.CreateRunspace();
            }
            else
            {
                initialSessionState = InitialSessionState.CreateDefault();
                string[] moduleFullPath = new string[modules.Length];
                for (int i = 0; i < modules.Length; i++)
                {
                    moduleFullPath[i] = modules[i].FullPath;
                    initialSessionState.Assemblies.Add(new SessionStateAssemblyEntry(modules[i].FullPath));
                }
                initialSessionState.ImportPSModule(moduleFullPath);

                runspace = RunspaceFactory.CreateRunspace(initialSessionState);
            }
        }
Пример #26
0
        public void TestInit()
        {
            testFiles = new List <String>();

            var initState = InitialSessionState.CreateDefault();

            initState.LanguageMode             = PSLanguageMode.FullLanguage;
            initState.ThrowOnRunspaceOpenError = true;
            initState.ThreadOptions            = PSThreadOptions.UseCurrentThread;

            var folder = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            initState.ImportPSModule(new string[] { System.IO.Path.Combine(folder, "RoboDave.dll") });

            runspace = RunspaceFactory.CreateRunspace(initState);
            runspace.Open();

            ps          = PowerShell.Create();
            ps.Runspace = runspace;
        }
        public async override Task InstallPackageAsync(SoftwarePackage package)
        {
            var fileinfo = await GetPackageFileAsync(package, ".appx");

            var sessionState = InitialSessionState.CreateDefault();

            sessionState.ExecutionPolicy = ExecutionPolicy.Unrestricted;

            using var ps = PowerShell.Create(sessionState);
            ps.AddScript($"cd \"{fileinfo.DirectoryName}\"");
            ps.AddScript("Import-Module Appx -UseWindowsPowerShell");
            ps.AddScript($"Add-AppxPackage '{package.PackageName}'");

            await ps.InvokeAsync();

            if (ps.HadErrors)
            {
                throw new InstallFailedException();
            }
        }
        /// <summary>
        /// This sample uses an InitialSessionState to create Runspace. It invokes
        /// a command from PowerShell snap-in present in the console file.
        /// </summary>
        /// <param name="args">Unused</param>
        /// <remarks>
        /// This sample assumes that user has the PowerShell binary module "GetProcessSample01.dll"
        /// produced in sample GetProcessSample01 copied to the current directory.
        ///
        ///     This sample demonstrates the following:
        ///         1. Creating a default instance of InitialSessionState
        ///         2. Using the InitialSessionState to create a runspace
        ///         3. Create a pipeline with the get-proc cmdlet available in the PowerShell binary module
        ///         4. Using PSObject to extract and display properties from the objects
        ///            returned by this command
        /// </remarks>
        static void Main(string[] args)
        {
            InitialSessionState iss = InitialSessionState.CreateDefault();
            PSSnapInException   warning;

            iss.ImportPSSnapIn("GetProcPSSnapIn01", out warning);

            // Create a runspace.
            // (Note that no PSHost instance is supplied to the CreateRunspace
            // function so the default PSHost implementation is used. See the
            // Hosting topics for more information on creating your own PSHost class.)

            Runspace myRunSpace = RunspaceFactory.CreateRunspace(iss);

            myRunSpace.Open();

            // Create a PowerShell with get-proc command.
            PowerShell powershell = PowerShell.Create().AddCommand("GetProcPSSnapIn01\\get-proc");

            powershell.Runspace = myRunSpace;

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

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

            // Print out each result object...
            foreach (PSObject result in results)
            {
                Console.WriteLine("{0,-20} {1}",
                                  result.Members["ProcessName"].Value,
                                  result.Members["HandleCount"].Value);
            }

            // Finally close the runspace
            // up any resources.
            myRunSpace.Close();

            System.Console.WriteLine("Hit any key to exit...");
            System.Console.ReadKey();
        }
Пример #29
0
        /// <summary>
        /// Executes the specified PowerShell script.
        /// </summary>
        /// <param name="scriptText"></param>
        /// <returns></returns>
        public static Collection <PSObject> ExecutePowerShellScript(string scriptText)
        {
            InitialSessionState iss = InitialSessionState.CreateDefault();
            PSSnapInException   warning;

            iss.ImportPSSnapIn("Microsoft.SharePoint.PowerShell", out warning);
            Collection <PSObject> results;

            // create Powershell runspace
            using (var runspace = RunspaceFactory.CreateRunspace(iss))
            {
                // open it
                runspace.Open();

                try
                {
                    // create a pipeline and feed it the script text
                    var pipeline = runspace.CreatePipeline();
                    pipeline.Commands.AddScript(scriptText);
                    pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);

                    try
                    {
                        // execute the script
                        results = pipeline.Invoke();
                    }
                    catch (Exception ex)
                    {
                        BaristaDiagnosticsService.Local.LogException(ex, BaristaDiagnosticCategory.PowerShell, "Unexpected Error while executing PowerShell Script:");
                        throw;
                    }
                }
                finally
                {
                    runspace.Close();
                }
            }

            //Return the results.
            return(results);
        }
Пример #30
0
        public string Run2(string script, IDictionary <string, object> parameters = null)
        {
            var outputStr = new StringBuilder();

            var initialSessionState = InitialSessionState.CreateDefault();

            initialSessionState.Variables.Add(new SessionStateVariableEntry("context", parameters, ""));

            using (Runspace runspace = RunspaceFactory.CreateRunspace(initialSessionState))
            {
                using (PowerShell powerShell = PowerShell.Create())
                {
                    // execute
                    runspace.Open();

                    powerShell.Runspace = runspace;
                    powerShell.AddScript(script);

                    var results = powerShell.Invoke <string>();

                    // output
                    foreach (var outputItem in results)
                    {
                        if (outputItem != null)
                        {
                            outputStr.AppendLine(outputItem.ToString());
                        }
                    }

                    // errors
                    foreach (ErrorRecord error in powerShell.Streams.Error.ReadAll())
                    {
                        outputStr.AppendLine(string.Format("{0} in line {1}, column {2}", error, error.InvocationInfo.ScriptLineNumber, error.InvocationInfo.OffsetInLine));
                    }

                    runspace.Close();
                }
            }

            return(outputStr.ToString());
        }