/// <summary>
        /// VerifyPrimaryServer method implementation
        /// </summary>
        internal static void VerifyPrimaryServer()
        {
            Runspace   SPRunSpace   = null;
            PowerShell SPPowerShell = null;

            try
            {
                RunspaceConfiguration SPRunConfig = RunspaceConfiguration.Create();
                SPRunSpace = RunspaceFactory.CreateRunspace(SPRunConfig);

                SPPowerShell          = PowerShell.Create();
                SPPowerShell.Runspace = SPRunSpace;
                SPRunSpace.Open();

                Pipeline pipeline  = SPRunSpace.CreatePipeline();
                Command  exportcmd = new Command("(Get-AdfsSyncProperties).Role", true);
                pipeline.Commands.Add(exportcmd);
                Collection <PSObject> PSOutput = pipeline.Invoke();
                foreach (var result in PSOutput)
                {
                    if (!result.BaseObject.ToString().ToLower().Equals("primarycomputer"))
                    {
                        throw new InvalidOperationException("PS0033: This Cmdlet cannot be executed from a secondary server !");
                    }
                }
            }
            finally
            {
                if (SPRunSpace != null)
                {
                    SPRunSpace.Close();
                }
            }
        }
Exemple #2
0
        private void AzureVM()
        {
            string path   = @"c:\Scripts\VMcreate.ps1";
            string VmName = DateTime.Now.ToString();
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

            using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
            {
                runspace.Open();
                RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
                //scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
                Pipeline pipeline      = runspace.CreatePipeline();
                Command  scriptCommand = new Command(path);
                Collection <CommandParameter> commandParameters = new Collection <CommandParameter>();

                /*
                 * foreach (string scriptParameter in parameters)
                 * {
                 *  CommandParameter commandParm = new CommandParameter(null, scriptParameter);
                 *  commandParameters.Add(commandParm);
                 *  scriptCommand.Parameters.Add(commandParm);
                 * }
                 */
                pipeline.Commands.Add(scriptCommand);
                Collection <PSObject> psObjects;
                psObjects = pipeline.Invoke();
            }
        }
Exemple #3
0
        /// <summary>Opens PowerShell runspace.</summary>
        /// <returns>The runspace.</returns>
        private Runspace OpenRunspace()
        {
            HostedSolutionLog.LogStart("OpenRunspace");

            if (runspaceConfiguration == null)
            {
                runspaceConfiguration = RunspaceConfiguration.Create();
                PSSnapInException exception;
                runspaceConfiguration.AddPSSnapIn(SharepointSnapInName, out exception);
                HostedSolutionLog.LogInfo("Sharepoint snapin loaded");

                if (exception != null)
                {
                    HostedSolutionLog.LogWarning("SnapIn error", exception);
                }
            }

            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);

            runspace.Open();
            runspace.SessionStateProxy.SetVariable("ConfirmPreference", "none");
            HostedSolutionLog.LogEnd("OpenRunspace");

            return(runspace);
        }
Exemple #4
0
        public void Provision(ImportBaseElement x, string templateRootFolder, string sharePointSiteUrl, string sharePointUserName, string sharePointPassword)
        {
            try
            {
                RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
                Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
                runspace.Open();
                RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

                Pipeline pipeline = runspace.CreatePipeline();

                var scriptPath = Path.Combine(templateRootFolder, x.SourceFolder, x.Handler.CustomCommand);

                Command myCommand = new Command(scriptPath, false);

                foreach (var p in x.Handler.CustomCommandArguments)
                {
                    myCommand.Parameters.Add(p.ParameterName, p.ParameterValue);
                }

                myCommand.Parameters.Add("SharePointSiteUrl", sharePointSiteUrl);
                myCommand.Parameters.Add("SharePointSiteUserName", sharePointUserName);
                myCommand.Parameters.Add("SharePointPassword", sharePointPassword);

                pipeline.Commands.Add(myCommand);
                Collection <PSObject> psObjects;
                psObjects = pipeline.Invoke();
                runspace.Close();
            }
            catch (Exception ex)
            {
                Console.Error.Write($"##vso[task.logissue type=error] Failed to Execute Powershell script with message {ex.Message}");
            }
        }
Exemple #5
0
        public List <string> RunPowershell(FunctionParamChart functionChart, List <Parameter> powershellParams)
        {
            var shellResult = new List <string>();

            if (powershellParams.Any(x => x.Value == null))
            {
                return(shellResult);
            }
            using (Runspace runspace = RunspaceFactory.CreateRunspace(RunspaceConfiguration.Create()))
            {
                runspace.Open();
                using (RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace))
                {
                    try
                    {
                        scriptInvoker.Invoke("Set-ExecutionPolicy -Scope CurrentUser Unrestricted");
                        using (PowerShell shell = PowerShell.Create())
                        {
                            shell.AddScript(functionChart.PowershellFileInfo.FullName);
                            string aggParam = string.Empty;
                            foreach (var param in powershellParams)
                            {
                                aggParam += " -" + param.Name + " " + param.Value;
                            }

                            using (var shellProcess = new Process())
                            {
                                shellProcess.StartInfo = new ProcessStartInfo
                                {
                                    FileName               = "Powershell.exe",
                                    Arguments              = functionChart.PowershellFileInfo.FullName + " " + aggParam,
                                    UseShellExecute        = false,
                                    RedirectStandardOutput = true,
                                    RedirectStandardError  = true,
                                    CreateNoWindow         = true
                                };

                                shellProcess.Start();

                                while (!shellProcess.StandardOutput.EndOfStream)
                                {
                                    shellResult.Add(shellProcess.StandardOutput.ReadLine() + Environment.NewLine);
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        shellResult.Add(e.Message);
                    }
                    finally
                    {
                        scriptInvoker.Invoke("Set-ExecutionPolicy -Scope CurrentUser Restricted");
                        runspace.Close();
                    }
                }
            }

            return(shellResult);
        }
    /// <summary>
    /// set the current runspace to local.
    /// Every command will be executed on the local machine
    /// </summary>
    public void SetLocalHost()
    {
        if (!this.m_runspaces.ContainsKey("localhost"))
        {
            RunspaceConfiguration rc = RunspaceConfiguration.Create();
            PSSnapInException     psSnapInException = null;
            switch (this.m_ExchangeVersion)
            {
            case ExchangeVersionEnum.v2010:
                rc.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out psSnapInException);
                break;

            case ExchangeVersionEnum.v2013:
                rc.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.SnapIn", out psSnapInException);
                break;
            }
            if (psSnapInException != null)
            {
                throw psSnapInException;
            }
            var runspace = RunspaceFactory.CreateRunspace(rc);
            runspace.Open();
            this.m_runspaces.Add("localhost", runspace);
        }
        this.Host = "localhost";
    }
Exemple #7
0
        static void ExecuteScriptFile()
        {
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);

            runspace.Open();

            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

            Pipeline pipeline = runspace.CreatePipeline();

            string scriptfile = AppDomain.CurrentDomain.BaseDirectory + "\\test.ps1";

            //Here's how you add a new script with arguments
            Command myCommand = new Command(scriptfile);

            //CommandParameter testParam = new CommandParameter("key", "value");
            //myCommand.Parameters.Add(testParam);

            myCommand.Parameters.Add(new CommandParameter("value01", Guid.NewGuid().ToString()));

            myCommand.Parameters.Add(new CommandParameter("value02", (new Random()).Next().ToString()));

            pipeline.Commands.Add(myCommand);

            // Execute PowerShell script
            Collection <PSObject> results = pipeline.Invoke();

            foreach (var item in results)
            {
                Console.WriteLine(item.BaseObject.ToString());
            }
        }
        public void execToPowerShell(string query, string ps1path)
        {
            try
            {
                //exec script
                RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
                Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);

                runspace.Open();
                RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
                Pipeline       pipeline      = runspace.CreatePipeline();
                Command        myCommand     = new Command(ps1path);
                //CommandParameter a = new CommandParameter("server", server);
                CommandParameter b = new CommandParameter("query", query);
                //myCommand.Parameters.Add(a);
                myCommand.Parameters.Add(b);
                pipeline.Commands.Add(myCommand);

                // Execute PowerShell script
                Collection <PSObject> results = pipeline.Invoke();

                //foreach (PSObject s in results)
                //{
                //    //Process p = s.BaseObject as Process;
                //    string e = s.Members["PercentComplete"].Value.ToString();
                //    MessageBox.Show(e);

                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.InnerException.Message);
            }
        }
        public void execToPowerShell(string[] server, string query, string ps1path)
        {
            try
            {
                //exec script
                RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
                Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);

                runspace.Open();
                RunspaceInvoke   scriptInvoker = new RunspaceInvoke(runspace);
                Pipeline         pipeline      = runspace.CreatePipeline();
                Command          myCommand     = new Command(ps1path);
                CommandParameter a             = new CommandParameter("server", server);
                CommandParameter b             = new CommandParameter("query", query);
                myCommand.Parameters.Add(a);
                myCommand.Parameters.Add(b);
                pipeline.Commands.Add(myCommand);

                // Execute PowerShell script
                Collection <PSObject> results = pipeline.Invoke();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.InnerException.Message);
            }
        }
Exemple #10
0
        private static void AdduserNotExpire(string fNm, string lNm, string uNm, string pWd, string gpUser)
        {
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);

            runspace.Open();
            RunspaceInvoke   scriptInvoker = new RunspaceInvoke(runspace);
            Pipeline         pipeline      = runspace.CreatePipeline();
            string           scriptfile    = @"C:\temp\addusernotexpire.ps1";
            Command          myCommand     = new Command(scriptfile);
            CommandParameter p1            = new CommandParameter("fname", fNm);
            CommandParameter p2            = new CommandParameter("lname", lNm);
            CommandParameter p3            = new CommandParameter("uname", uNm);
            CommandParameter p4            = new CommandParameter("pWd", pWd);
            CommandParameter p5            = new CommandParameter("grpUser", gpUser);

            myCommand.Parameters.Add(p1);
            myCommand.Parameters.Add(p2);
            myCommand.Parameters.Add(p3);
            myCommand.Parameters.Add(p4);
            myCommand.Parameters.Add(p5);
            pipeline.Commands.Add(myCommand);
            // invoke execution on the pipeline (ignore output)
            pipeline.Invoke();
        }
Exemple #11
0
        private void ShowInfo()
        {
            try
            {
                var runspaceConfiguration = RunspaceConfiguration.Create();

                using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
                {
                    runspace.Open();

                    using (var scriptInvoker = new RunspaceInvoke(runspace))
                    {
                        scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
                        using (var pipeline = runspace.CreatePipeline())
                        {
                            Command myCommand = new Command(@".\Command.ps1");
                            pipeline.Commands.Add(myCommand);

                            var res = pipeline.Invoke();
                            this.notifyIcon1.BalloonTipText = res.Aggregate("", (c, n) => this.FormatOutput(c, n.BaseObject.ToString()));
                            if (string.IsNullOrEmpty(this.notifyIcon1.BalloonTipText))
                            {
                                this.notifyIcon1.BalloonTipText = "script returns no results";
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.notifyIcon1.BalloonTipText = ex.ToString();
            }

            this.notifyIcon1.ShowBalloonTip(500);
        }
Exemple #12
0
        public static void Main(string[] args)
        {
            try
            {
                var scriptFile            = @"C:\Development\PowerShell\ImportSqlServerBacpac.ps1";
                var runSpaceConfiguration = RunspaceConfiguration.Create();
                var runSpace = RunspaceFactory.CreateRunspace(runSpaceConfiguration);
                runSpace.Open();
                using (var scriptInvoker = new RunspaceInvoke(runSpace))
                {
                    scriptInvoker.Invoke("Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass");
                    var pipeline = runSpace.CreatePipeline();
                    //Here's how you add a new script with arguments
                    var myCommand = new Command(scriptFile);

                    /*var testParam = new CommandParameter("key", "value");
                     * myCommand.Parameters.Add(testParam);*/
                    pipeline.Commands.Add(myCommand);
                    // Execute PowerShell script
                    var results = pipeline.Invoke();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
        }
        /// <summary>
        /// AddFirewallRules method implmentation
        /// </summary>
        /// <param name="lst"></param>
        internal static void AddFirewallRules(string computers)
        {
            Runspace   SPRunSpace   = null;
            PowerShell SPPowerShell = null;

            try
            {
                RunspaceConfiguration SPRunConfig = RunspaceConfiguration.Create();
                SPRunSpace = RunspaceFactory.CreateRunspace(SPRunConfig);

                SPPowerShell          = PowerShell.Create();
                SPPowerShell.Runspace = SPRunSpace;
                SPRunSpace.Open();

                Pipeline pipeline = SPRunSpace.CreatePipeline();
                Command  rulein1  = new Command("New-NetFirewallRule -Name 'MFAIN1' -DisplayName 'MFA IN Notification Service UDP' -Group 'MFA' -Profile @('Domain') -Direction Inbound -Action Allow -Protocol UDP -LocalPort @('137', '138') -RemoteAddress " + computers, true);
                Command  rulein2  = new Command("New-NetFirewallRule -Name 'MFAIN2'  -DisplayName 'MFA IN Notification Service TCP' -Group 'MFA' -Profile @('Domain') -Direction Inbound -Action Allow -Protocol TCP -LocalPort @('139', '445') -RemoteAddress " + computers, true);
                Command  ruleout1 = new Command("New-NetFirewallRule -Name 'MFAOUT1'  -DisplayName 'MFA OUT Notification Service UDP' -Group 'MFA' -Profile @('Domain') -Direction Outbound -Action Allow -Protocol UDP -LocalPort @('137', '138') -RemoteAddress " + computers, true);
                Command  ruleout2 = new Command("New-NetFirewallRule -Name 'MFAOUT2'  -DisplayName 'MFA OUT Notification Service TCP' -Group 'MFA' -Profile @('Domain') -Direction Outbound -Action Allow -Protocol TCP -LocalPort @('139', '445') -RemoteAddress " + computers, true);
                pipeline.Commands.Add(rulein1);
                pipeline.Commands.Add(rulein2);
                pipeline.Commands.Add(ruleout1);
                pipeline.Commands.Add(ruleout2);
                pipeline.Invoke();
            }
            finally
            {
                if (SPRunSpace != null)
                {
                    SPRunSpace.Close();
                }
            }
        }
        /// <summary>
        /// RemoveFirewallRules method implementation
        /// </summary>
        internal static void RemoveFirewallRules()
        {
            Runspace   SPRunSpace   = null;
            PowerShell SPPowerShell = null;

            try
            {
                RunspaceConfiguration SPRunConfig = RunspaceConfiguration.Create();
                SPRunSpace = RunspaceFactory.CreateRunspace(SPRunConfig);

                SPPowerShell          = PowerShell.Create();
                SPPowerShell.Runspace = SPRunSpace;
                SPRunSpace.Open();

                Pipeline pipeline = SPRunSpace.CreatePipeline();
                Command  rulein1  = new Command("Remove-NetFirewallRule -Name 'MFAIN1' ", true);
                Command  rulein2  = new Command("Remove-NetFirewallRule -Name 'MFAIN2' ", true);
                Command  ruleout1 = new Command("Remove-NetFirewallRule -Name 'MFAOUT1' ", true);
                Command  ruleout2 = new Command("Remove-NetFirewallRule -Name 'MFAOUT2' ", true);
                pipeline.Commands.Add(rulein1);
                pipeline.Commands.Add(rulein2);
                pipeline.Commands.Add(ruleout1);
                pipeline.Commands.Add(ruleout2);
                pipeline.Invoke();
            }
            finally
            {
                if (SPRunSpace != null)
                {
                    SPRunSpace.Close();
                }
            }
        }
            public override RunspaceConfiguration CreateRunspaceConfiguration()
            {
                RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

                AnchorRunspaceProxy.FullExchangeRunspaceConfigurationFactory.AddPSSnapIn(runspaceConfiguration, "Microsoft.Exchange.Management.PowerShell.E2010");
                return(runspaceConfiguration);
            }
Exemple #16
0
        /// <summary>
        /// InitServerNodeConfiguration2012 method implementation
        /// </summary>
        public static string InitServerNodeType()
        {
            string     nodetype     = string.Empty;
            Runspace   SPRunSpace   = null;
            PowerShell SPPowerShell = null;

            try
            {
                RunspaceConfiguration SPRunConfig = RunspaceConfiguration.Create();
                SPRunSpace            = RunspaceFactory.CreateRunspace(SPRunConfig);
                SPPowerShell          = PowerShell.Create();
                SPPowerShell.Runspace = SPRunSpace;
                SPRunSpace.Open();

                Pipeline pipeline  = SPRunSpace.CreatePipeline();
                Command  exportcmd = new Command("(Get-AdfsSyncProperties).Role", true);
                pipeline.Commands.Add(exportcmd);

                Collection <PSObject> PSOutput = pipeline.Invoke();
                foreach (var prop in PSOutput)
                {
                    nodetype = prop.BaseObject.ToString();
                    break;
                }
            }
            finally
            {
                if (SPRunSpace != null)
                {
                    SPRunSpace.Close();
                }
            }
            return(nodetype);
        }
Exemple #17
0
        private bool PluginRegistered()
        {
            // load PowerShell
            Runspace runSpace;

            var rsConfig = RunspaceConfiguration.Create();

            runSpace = RunspaceFactory.CreateRunspace(rsConfig);
            runSpace.Open();

            using (var ps = PowerShell.Create())
            {
                ps.Runspace = runSpace;
                ps.AddCommand("Get-PSSnapin");
                ps.AddParameter("Registered");
                ps.AddParameter("Name", "OSA");
                var result = ps.Invoke();
                if (result.Count == 0)
                {
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
        }
Exemple #18
0
        public static void SetProfile(LanguageProfile profile)
        {
            RunspaceConfiguration psConfig = RunspaceConfiguration.Create();
            var psRunspace = RunspaceFactory.CreateRunspace(psConfig);

            psRunspace.Open();

            using (Pipeline psPipeline = psRunspace.CreatePipeline())
            {
                Command command  = new Command("Set-WinUserLanguageList");
                var     langType = Type.GetType(AppConfig.CurrentConfig.InternalAppConfig.WinUserLanguageType);
                IList   langList = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(langType));

                foreach (var tag in profile.LanguageTags)
                {
                    var lang = Activator.CreateInstance(langType, tag);
                    langList.Add(lang);
                }

                psPipeline.Commands.Add(command);
                command.Parameters.Add("LanguageList", langList);
                command.Parameters.Add("Force", true);

                psPipeline.Invoke();
            }
        }
        internal static LanguageProfile InternalGetCurrentLanguageProfile(string name, out Type winUserLanguageType)
        {
            RunspaceConfiguration psConfig = RunspaceConfiguration.Create();
            var psRunspace = RunspaceFactory.CreateRunspace(psConfig);

            psRunspace.Open();
            List <string> languageTags = new List <string>();

            using (Pipeline psPipeline = psRunspace.CreatePipeline())
            {
                Command command = new Command("Get-WinUserLanguageList");

                psPipeline.Commands.Add(command);

                var     results = psPipeline.Invoke();
                dynamic member  = results.First().BaseObject;

                winUserLanguageType = member[0].GetType();

                foreach (var mem in member)
                {
                    languageTags.Add(mem.LanguageTag);
                }
            }

            var languageProfile = new LanguageProfile()
            {
                LanguageTags = languageTags, Name = name
            };

            return(languageProfile);
        }
Exemple #20
0
    public static string Exec()
    {
        RunspaceConfiguration rsconfig = RunspaceConfiguration.Create();
        Runspace runspace = RunspaceFactory.CreateRunspace(rsconfig);

        runspace.Open();
        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
        Pipeline       pipeline      = runspace.CreatePipeline();

        // our malicious command
        String cmd = "Start-Process notepad.exe";

        pipeline.Commands.AddScript(cmd);

        // added for easier output
        pipeline.Commands.Add("Out-String");
        Collection <PSObject> results = pipeline.Invoke();

        runspace.Close();

        // convert records to strings
        StringBuilder stringBuilder = new StringBuilder();

        foreach (PSObject obj in results)
        {
            stringBuilder.Append(obj);
        }
        return(stringBuilder.ToString().Trim());
    }
Exemple #21
0
        private void InitializeRunspaceAndHost()
        {
            if (null == _shellConfiguration.RunspaceConfiguration)
            {
                _shellConfiguration.RunspaceConfiguration = RunspaceConfiguration.Create();
            }

            _shellConfiguration.Cmdlets.ToList().ForEach(
                cce => _shellConfiguration.RunspaceConfiguration.Cmdlets.Append(cce)
                );

            _rawUi  = new HostRawUI(_consoleWindow, _shellConfiguration.ShellName);
            _hostUi = new HostUI(_consoleWindow, _shellConfiguration.UISettings, _rawUi);
            _host   = new Host.Host(_shellConfiguration.ShellName, _shellConfiguration.ShellVersion, _hostUi,
                                    _shellConfiguration.RunspaceConfiguration);

            _hostUi.Progress += NotifyProgress;

            _runspace = _host.Runspace;
            _runspace.Open();

            _commandExecutor = new Executor(_runspace);

            _shellConfiguration.InitialVariables.ToList().ForEach(pair =>
                                                                  _runspace.SessionStateProxy.PSVariable.Set(pair)
                                                                  );
        }
Exemple #22
0
        void InitializeOldSkoolShell()
        {
            var thread = new System.Threading.Thread(() =>
            {
                var config = RunspaceConfiguration.Create();

                config.InitializationScripts.Append(new ScriptConfigurationEntry(
                                                        "warn-defaultconsole",
                                                        Scripts.WarnDefaultConsole
                                                        )
                                                    );

                config.InitializationScripts.Append(new ScriptConfigurationEntry(
                                                        "start-studioshell",
                                                        Scripts.StartStudioShell
                                                        )
                                                    );

                config.InitializationScripts.Append(new ScriptConfigurationEntry(
                                                        "start-profile",
                                                        Scripts.CreateRunProfileScript(new StudioShellProfileInfo())
                                                        )
                                                    );

                AllocConsole();
                Microsoft.PowerShell.ConsoleShell.Start(
                    config,
                    "Visual Studio Default Process Console",
                    "",
                    new string[] {});
            });

            thread.Start();
        }
        internal virtual Runspace OpenRunspace()
        {
            ExchangeLog.LogStart("OpenRunspace");

            if (runspaceConfiguration == null)
            {
                runspaceConfiguration = RunspaceConfiguration.Create();
                PSSnapInException exception = null;

                PSSnapInInfo info = runspaceConfiguration.AddPSSnapIn(ExchangeSnapInName, out exception);

                if (exception != null)
                {
                    ExchangeLog.LogWarning("SnapIn error", exception);
                }
            }
            Runspace runSpace = RunspaceFactory.CreateRunspace(runspaceConfiguration);

            //AdminSessionADSettings adSettings = SetADSettings();
            runSpace.Open();
            //runSpace.SessionStateProxy.SetVariable("AdminSessionADSettings", adSettings);
            runSpace.SessionStateProxy.SetVariable("ConfirmPreference", "none");
            ExchangeLog.LogEnd("OpenRunspace");
            return(runSpace);
        }
Exemple #24
0
        private static Collection <PSObject> Demo5(string filePath, string parameters)
        {
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);

            runspace.Open();
            RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
            Pipeline       pipeline      = runspace.CreatePipeline();
            Command        scriptCommand = new Command(filePath);
            Collection <CommandParameter> commandParameters = new Collection <CommandParameter>();

            string[] tempParas = parameters.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < tempParas.Length; i += 2)
            {
                CommandParameter commandParm = new CommandParameter(tempParas[i], tempParas[i + 1]);
                commandParameters.Add(commandParm);
                scriptCommand.Parameters.Add(commandParm);
            }

            pipeline.Commands.Add(scriptCommand);
            var psObjects = pipeline.Invoke();

            if (pipeline.Error.Count > 0)
            {
                throw new Exception("脚本执行失败");
            }

            runspace.Close();

            return(psObjects);
        }
Exemple #25
0
        /// <summary>	Gets a job. </summary>
        /// <remarks>	Anthony, 5/29/2015. </remarks>
        /// <param name="jobId">	Identifier for the job. </param>
        /// <returns>	The job. </returns>
        public Task <PowershellReturn> GetJob(Guid jobId)
        {
            RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();

            InitialSessionState initialSession = InitialSessionState.Create();

            using (PowerShell powerShellInstance = PowerShell.Create(initialSession))
            {
                powerShellInstance.RunspacePool = RunspacePoolWrapper.Pool;
                if (powerShellInstance.Runspace == null)
                {
                    powerShellInstance.Runspace = RunspaceFactory.CreateRunspace(rsConfig);
                    powerShellInstance.Runspace.Open();
                }

                ICollection <PSJobProxy> jobProxyCollection = PSJobProxy.Create(powerShellInstance.Runspace);

                var proxy = jobProxyCollection.First();

                return(Task.FromResult(
                           new PowershellReturn
                {
                    PowerShellReturnedValidData = true,
                    ActualPowerShellData = proxy.Output.LastOrDefault().ToString()
                }
                           ));
            }
        }
Exemple #26
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string command = @in.Text;

            @out.Text += command + "\r\n";
            RunspaceConfiguration rspacecfg = RunspaceConfiguration.Create();
            Runspace rspace = RunspaceFactory.CreateRunspace(rspacecfg);

            rspace.Open();
            Pipeline pipeline = rspace.CreatePipeline();

            pipeline.Commands.AddScript(command);
            pipeline.InvokeAsync();
            while (pipeline.PipelineStateInfo.State == PipelineState.Running || pipeline.PipelineStateInfo.State == PipelineState.Stopping)
            {
                System.Threading.Thread.Sleep(50);
            }
            foreach (object item in pipeline.Output.ReadToEnd())
            {
                if (item != null)
                {
                    @out.Text += item.ToString() + "\r\n";
                }
            }
            foreach (object item in pipeline.Error.ReadToEnd())
            {
                if (item != null)
                {
                    @out.Text += item.ToString() + "\r\n";
                }
            }
        }
        public static Collection <PSObject> RunScript(ScriptObject script)
        {
            if (script.IsRunning)
            {
                return(null);
            }

            var res = new Collection <PSObject>();

            script.IsRunning = true;

            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

            using (Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration))
            {
                runspace.Open();
                var scriptPath = Path.Combine(ScriptFolderPath, script.ScriptName);
                runspace.SessionStateProxy.Path.SetLocation(ScriptFolderPath);

                using (Pipeline pipeline = runspace.CreatePipeline())
                {
                    Command cmd = new Command(scriptPath, false, false);

                    if (script.ScriptArgs != null)
                    {
                        foreach (var arg in script.ScriptArgs)
                        {
                            CommandParameter testParam = new CommandParameter(arg.Key, arg.Value);
                            cmd.Parameters.Add(testParam);
                        }
                    }

                    pipeline.Commands.Add(cmd);

                    try
                    {
                        res = pipeline.Invoke();
                    }
                    catch (ParseException ex)
                    {
                        var msg = string.Format("Exception: ParseException: {0}\n{1}", ex.Message, ex.ErrorRecord.ScriptStackTrace);
                        res.Add(msg);
                    }
                    catch (RuntimeException ex)
                    {
                        var msg = string.Format("Exception: RuntimeException: {0}\n{1}", ex.Message, ex.ErrorRecord.ScriptStackTrace);
                        res.Add(msg);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Unknown error occured executing Powershell script", ex);
                    }
                    finally
                    {
                        script.IsRunning = false;
                    }
                    return(res);
                }
            }
        }
        public static Collection <PSObject> RunScript(string scriptfile, string pKey1 = "", string pValue1 = "")
        {
            var runspaceConfiguration = RunspaceConfiguration.Create();
            var runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);

            runspace.Open();

            var scriptInvoker = new RunspaceInvoke(runspace);
            var pipeline      = runspace.CreatePipeline();

            // Here's how you add a new script with arguments
            var rolePath  = Environment.GetEnvironmentVariable("RoleRoot");
            var path      = Path.Combine(rolePath, "approot", "bin", "scripts");
            var myCommand = new Command(Path.Combine(path, scriptfile));

            if (!String.IsNullOrEmpty(pKey1))
            {
                var testParam = new CommandParameter(pKey1, pValue1);
                myCommand.Parameters.Add(testParam);
            }

            pipeline.Commands.Add(myCommand);

            // Execute PowerShell script
            var results = pipeline.Invoke();

            return(results);
        }
Exemple #29
0
        /// <summary>
        /// 파워셀 - db 원격스크립트 수행 - 티베로 gisLoader, tbloader
        /// </summary>
        /// <param name="scriptfile"></param>
        private void ExPsScript(string scriptfile)
        {
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();

            Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);

            runspace.Open();

            RunspaceInvoke scriptInvoker = new RunspaceInvoke();

            scriptInvoker.Invoke("Set-ExecutionPolicy RemoteSigned");

            Pipeline pipeline = runspace.CreatePipeline();

            //Here's how you add a new script with arguments
            Command myCommand = new Command(scriptfile);

            //CommandParameter testParam = new CommandParameter("key", "value");
            //myCommand.Parameters.Add(testParam);

            pipeline.Commands.Add(myCommand);

            // Execute PowerShell script
            pipeline.Invoke();
        }
Exemple #30
0
        /// <summary>
        /// Create the runspace and add the cmdlet to it
        /// </summary>
        private static Runspace CreateRunspace(string name, Type cmdlet)
        {
            var config = RunspaceConfiguration.Create();

            config.Cmdlets.Append(new [] { new CmdletConfigurationEntry(name, cmdlet, "") });
            return(RunspaceFactory.CreateRunspace(config));
        }