/// <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";
    }
Exemplo n.º 2
0
        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);
        }
Exemplo n.º 3
0
        public ExchangeCommandResolver(IEnumerable <string> snapIns)
        {
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
            PSSnapInException     ex         = null;
            Exception             ex2        = null;
            IEnumerable <string>  enumerable = (from s in snapIns
                                                select s.ToLower()).Distinct <string>();

            foreach (string name in enumerable)
            {
                try
                {
                    runspaceConfiguration.AddPSSnapIn(name, out ex);
                    ex2 = ex;
                }
                catch (PSArgumentException ex3)
                {
                    ex2 = ex3;
                }
                if (ex2 != null)
                {
                    ReportingWebServiceEventLogConstants.Tuple_LoadReportingschemaFailed.LogEvent(new object[]
                    {
                        ex2.Message
                    });
                    ServiceDiagnostics.ThrowError(ReportingErrorCode.ErrorSchemaInitializationFail, Strings.ErrorSchemaInitializationFail, ex2);
                }
            }
            this.runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
            if (this.runspace.RunspaceStateInfo.State != RunspaceState.Opened)
            {
                this.runspace.Open();
            }
        }
Exemplo n.º 4
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);
        }
Exemplo n.º 5
0
            private static void AddPSSnapIn(RunspaceConfiguration runspaceConfiguration, string mshSnapInName)
            {
                PSSnapInException ex = null;

                runspaceConfiguration.AddPSSnapIn(mshSnapInName, out ex);
                if (ex != null)
                {
                    throw new CouldNotAddExchangeSnapInTransientException(mshSnapInName, ex);
                }
            }
Exemplo n.º 6
0
        public void InitializeTests()
        {
            RunspaceConfiguration config = RunspaceConfiguration.Create();

            PSSnapInException warning;

            config.AddPSSnapIn("ShareFile", out warning);

            runspace = RunspaceFactory.CreateRunspace(config);
            runspace.Open();
        }
        private Runspace GetConnectorPowershellRunspace()
        {
            RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
            PSSnapInException     ex = null;

            runspaceConfiguration.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out ex);
            if (ex != null)
            {
                throw ex;
            }
            return(RunspaceFactory.CreateRunspace(runspaceConfiguration));
        }
Exemplo n.º 8
0
        private void RunNormal()
        {
            Pipeline pipeline = null;
            Runspace runspace = null;

            try
            {
                RunspaceConfiguration runConfig = RunspaceConfiguration.Create();

                PSSnapInException psEx   = null;
                string            script = OSAEScriptManager.GetScriptByName(Name);
                runConfig.AddPSSnapIn("OSA", out psEx);
                runspace = RunspaceFactory.CreateRunspace(runConfig);
                runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;

                runspace.Open();

                runspace.SessionStateProxy.SetVariable("parameter2", Parameter2);

                pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript(script);
                pipeline.Commands.Add("Out-String");

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

                StringBuilder stringBuilder = new StringBuilder();
                foreach (PSObject obj in results)
                {
                    stringBuilder.AppendLine(obj.ToString());
                }

                logging.AddToLog("Script return: \r\n" + stringBuilder.ToString(), false);
            }
            catch (Exception ex)
            {
                logging.AddToLog("An error occured while trying to run the script, details: \r\n" + ex.Message, true);
            }
            finally
            {
                if (pipeline != null)
                {
                    pipeline.Dispose();
                }
                if (runspace != null)
                {
                    runspace.Close();
                    runspace.Dispose();
                }
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Runs the content of the script parameter as a powershell script
        /// </summary>
        /// <param name="script">The script to be run</param>
        private void RunScript(string script, OSAEMethod method)
        {
            Pipeline pipeline = null;
            Runspace runspace = null;

            try
            {
                RunspaceConfiguration runConfig = RunspaceConfiguration.Create();

                PSSnapInException psEx = null;

                runConfig.AddPSSnapIn("OSA", out psEx);
                runspace = RunspaceFactory.CreateRunspace(runConfig);
                runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;

                runspace.Open();

                runspace.SessionStateProxy.SetVariable("parameter2", method.Parameter2);

                pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript(script);
                pipeline.Commands.Add("Out-String");

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

                StringBuilder stringBuilder = new StringBuilder();
                foreach (PSObject obj in results)
                {
                    stringBuilder.AppendLine(obj.ToString());
                }

                this.Log.Debug("Script return: " + stringBuilder.ToString());
            }
            catch (Exception ex)
            {
                this.Log.Error("An error occured while trying to run the script, details", ex);
            }
            finally
            {
                if (pipeline != null)
                {
                    pipeline.Dispose();
                }
                if (runspace != null)
                {
                    runspace.Close();
                    runspace.Dispose();
                }
            }
        }
        private static void AddPSSnapIn(RunspaceConfiguration runspaceConfiguration, string mshSnapInName)
        {
            PSSnapInException ex           = null;
            PSSnapInInfo      pssnapInInfo = runspaceConfiguration.AddPSSnapIn(mshSnapInName, out ex);

            if (ex != null)
            {
                throw ex;
            }
            if (pssnapInInfo != null)
            {
                ExTraceGlobals.IntegrationTracer.Information(0L, mshSnapInName + " added to Runspace:" + pssnapInInfo.ToString());
            }
        }
        private Collection <PSObject> RunPsScriptTBD(string psScriptPath)
        {
            string psScript = string.Empty;

            if (File.Exists(psScriptPath))
            {
                psScript = File.ReadAllText(psScriptPath);
            }
            else
            {
                throw new FileNotFoundException("Wrong path for the script file");
            }
            RunspaceConfiguration config = RunspaceConfiguration.Create();
            PSSnapInException     psEx;
            //add Microsoft SharePoint PowerShell SnapIn
            PSSnapInInfo pssnap = config.AddPSSnapIn("Microsoft.SharePoint.PowerShell", out psEx);
            //create powershell runspace
            Runspace cmdlet = RunspaceFactory.CreateRunspace(config);

            cmdlet.Open();
            RunspaceInvoke scriptInvoker = new RunspaceInvoke(cmdlet);

            // set powershell execution policy to unrestricted
            scriptInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
            // create a pipeline and load it with command object
            Pipeline pipeline = cmdlet.CreatePipeline();

            try
            {
                // Using Get-SPFarm powershell command
                pipeline.Commands.AddScript(psScript);
                pipeline.Commands.AddScript("Out-String");
                // this will format the output
                Collection <PSObject> output = pipeline.Invoke();
                pipeline.Stop();
                cmdlet.Close();
                // process each object in the output and append to stringbuilder
                StringBuilder results = new StringBuilder();
                foreach (PSObject obj in output)
                {
                    results.AppendLine(obj.ToString());
                }
                return(output);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Exemplo n.º 12
0
    public Collection <PSObject> ExecuteCommand(Command command)
    {
        RunspaceConfiguration runspaceConf = RunspaceConfiguration.Create();
        PSSnapInException     PSException  = null;
        PSSnapInInfo          info         = runspaceConf.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out PSException);
        Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConf);

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

        pipeline.Commands.Add(command);
        Collection <PSObject> result = pipeline.Invoke();

        return(result);
    }
Exemplo n.º 13
0
        /// <summary>
        /// This sample introduces how to add a PSSnapin to RunspaceConfiguration and
        /// then use modified RunspaceConfiguration to create the Runspace.
        /// </summary>
        /// <param name="args">Unused</param>
        /// <remarks>
        /// This sample assumes that user has the PowerShell snap-in "GetProcPSSnapIn01"
        /// produced in sample GetProcessSample01 installed on the machine.
        ///
        ///     This sample demonstrates the following:
        ///         1. Creating an instance of RunspaceConfiguration
        ///         2. Adding a PowerShell snap-in to this configuration
        ///         3. Using the configuration to create a runspace
        ///         4. Create a pipeline with the get-proc cmdlet available in the PowerShell snap-in
        ///         5. Using PSObject to extract and display properties from the objects
        ///            returned by this command
        /// </remarks>
        static void Main(string[] args)
        {
            //Create a default RunspaceConfiguration
            RunspaceConfiguration config = RunspaceConfiguration.Create();

            //Add GetProcPSSnapIn01 to config.
            PSSnapInException warning;

            config.AddPSSnapIn("GetProcPSSnapIn01", out warning);
            if (warning != null)
            {
                //We don't expect any warning so write the warning and return
                System.Console.Write(warning.Message);
                return;
            }

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

            Runspace myRunSpace = RunspaceFactory.CreateRunspace(config);

            myRunSpace.Open();

            // Create a pipeline with get-proc command from PowerShell snap-in GetProcPSSnapIn01.
            Pipeline pipeLine             = myRunSpace.CreatePipeline("GetProcPSSnapIn01\\get-proc");
            Collection <PSObject> results = pipeLine.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();
        }
Exemplo n.º 14
0
        static PSCommandBase()
        {
            lock (sync)
            {
                if (_runspace != null && _runspace.RunspaceStateInfo.State == RunspaceState.Broken)
                {
                    _runspace.Close();
                    _runspace.Dispose();
                }
                _runspaceConfiguration = RunspaceConfiguration.Create();
                _runspaceConfiguration.AddPSSnapIn(EXCHANGE_MANAGEMENT_ADMIN, out _psSnapinException);
                _runspace = RunspaceFactory.CreateRunspace(_runspaceConfiguration);
                _runspace.Open();

                // _runspace.SessionStateProxy.SetVariable("ConfirmPreference", "none");
            }
        }
Exemplo n.º 15
0
        private static void ReOpen()
        {
            lock (sync)
            {
                #region modfiy by 2016/09/01
                if (_runspace != null && _runspace.RunspaceStateInfo.State == RunspaceState.Broken)
                {
                    _runspace.Close();
                    _runspace.Dispose();
                }
                _runspaceConfiguration = RunspaceConfiguration.Create();
                _runspaceConfiguration.AddPSSnapIn(EXCHANGE_MANAGEMENT_ADMIN, out _psSnapinException);
                _runspace = RunspaceFactory.CreateRunspace(_runspaceConfiguration);
                _runspace.Open();

                // _runspace.SessionStateProxy.SetVariable("ConfirmPreference", "none");

                #endregion
            }
        }
Exemplo n.º 16
0
        public void InitializeTests()
        {
            RunspaceConfiguration config = RunspaceConfiguration.Create();

            PSSnapInException warning;

            config.AddPSSnapIn("ShareFile", out warning);

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

            // do login first to start tests
            using (Pipeline pipeline = runspace.CreatePipeline())
            {
                Command command = new Command("Get-SfClient");
                command.Parameters.Add(new CommandParameter("Name", Utils.LoginFilePath));

                pipeline.Commands.Add(command);

                Collection <PSObject> psObjects = pipeline.Invoke();
                Assert.AreEqual <int>(1, psObjects.Count);
                sfLogin = psObjects[0];
            }

            using (Pipeline pipeline = runspace.CreatePipeline())
            {
                Command command = new Command("New-PSDrive");
                command.Parameters.Add("Name", Utils.ShareFileDriveLetter);
                command.Parameters.Add("PSProvider", "ShareFile");
                command.Parameters.Add("Root", "/");
                command.Parameters.Add("Client", sfLogin);

                pipeline.Commands.Add(command);

                Collection <PSObject> psObjects = pipeline.Invoke();

                // Drive is successfully mapped to root folder
                Assert.AreEqual <int>(1, psObjects.Count);
            }
        }
Exemplo n.º 17
0
 private static bool RunScript(string cmd)
 {
     // create Powershell runspace
     try {
         RunspaceConfiguration rsConfig        = RunspaceConfiguration.Create();
         PSSnapInException     snapInException = null;
         PSSnapInInfo          info            = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapInException);
         Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);
         myRunSpace.Open();
         Pipeline pipeLine  = myRunSpace.CreatePipeline();
         Command  myCommand = new Command(cmd, true);
         pipeLine.Commands.Add(myCommand);
         Collection <PSObject> commandResults = pipeLine.Invoke();
         foreach (PSObject obj in commandResults)
         {
             Console.WriteLine(obj.ToString());
         }
         return(true);
     } catch (Exception ex) {
         return(false);
     }
 }
Exemplo n.º 18
0
 private void RunPowerShell()
 {
     //create the runspace
     runSpace = RunspaceFactory.CreateRunspace(rsConfig);
     runSpace.Open();
     rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapInException);
     //set up the pipeline to run the powershell command 
     Pipeline pipeLine = runSpace.CreatePipeline();
     
     //create the script to run
     String sScript = "get-mailbox -identity 'rj'";
     //invoke the command
     pipeLine.Commands.AddScript(sScript);
     Collection<PSObject> commandResults = pipeLine.Invoke();
     //loop through the results of the command and load the SamAccountName into the list
     foreach (PSObject results in commandResults)
     {
         Console.WriteLine(results.Properties["SamAccountName"].Value.ToString());
     }
     pipeLine.Dispose();
     runSpace.Close();
 }
Exemplo n.º 19
0
        public void InitializeTests()
        {
            RunspaceConfiguration config = RunspaceConfiguration.Create();

            PSSnapInException warning;

            config.AddPSSnapIn("ShareFile", out warning);

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

            // do login first to start tests
            using (Pipeline pipeline = runspace.CreatePipeline())
            {
                Command command = new Command("Get-SfClient");
                command.Parameters.Add(new CommandParameter("Name", Utils.LoginFilePath));

                pipeline.Commands.Add(command);

                Collection <PSObject> objs = pipeline.Invoke();
                Assert.AreEqual <int>(1, objs.Count);
                sfLogin = objs[0];
            }
        }
Exemplo n.º 20
0
        public Runspace DefaultRunspaceCreateMethod()
        {
            LOGGER.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "Creating runspace configuration");
            RunspaceConfiguration runSpaceConfig = RunspaceConfiguration.Create();

            if (_localSnapinNames != null)
            {
                foreach (string snapinName in _localSnapinNames)
                {
                    LOGGER.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "Adding snap-in {0}", snapinName);
                    PSSnapInException snapOutput = null;
                    runSpaceConfig.AddPSSnapIn(snapinName, out snapOutput);
                    if (snapOutput != null)
                    {
                        throw snapOutput;
                    }
                }
            }
            LOGGER.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "Creating the runspace");
            var runspace = RunspaceFactory.CreateRunspace(runSpaceConfig);

            LOGGER.TraceEvent(TraceEventType.Verbose, CAT_DEFAULT, "Runspace created");
            return(runspace);
        }
Exemplo n.º 21
0
        public Runspace DefaultRunspaceCreateMethod()
        {
            LOG.Trace("Creating runspace configuration");
            RunspaceConfiguration runSpaceConfig = RunspaceConfiguration.Create();

            if (_localSnapinNames != null)
            {
                foreach (string snapinName in _localSnapinNames)
                {
                    LOG.Debug("Adding snap-in {0}", snapinName);
                    PSSnapInException snapOutput = null;
                    runSpaceConfig.AddPSSnapIn(snapinName, out snapOutput);
                    if (snapOutput != null)
                    {
                        throw snapOutput;
                    }
                }
            }
            LOG.Trace("Creating the runspace");
            var runspace = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(new string[0]));

            LOG.Trace("Runspace created");
            return(runspace);
        }
Exemplo n.º 22
0
        /// <summary>	The asynchronous execution method. </summary>
        /// <remarks>	Anthony, 5/27/2015. </remarks>
        /// <exception cref="ArgumentException">		    Thrown when one or more arguments have
        ///                                                 unsupported or illegal values. </exception>
        /// <exception cref="ArgumentNullException">	    Thrown when one or more required arguments
        ///                                                 are null. </exception>
        /// <exception cref="PSSnapInException">		    . </exception>
        /// <exception cref="PowerShellExecutionException">	Thrown when a Power Shell Execution error
        ///                                                 condition occurs. </exception>
        /// <param name="filename">		    The filename. </param>
        /// <param name="snapin">		    The snap in. </param>
        /// <param name="module">		    The module. </param>
        /// <param name="parametersList">	The parameters List. </param>
        /// <param name="asJob">		    Run this command as a job. </param>
        /// <returns>	The <see cref="Task"/>. </returns>
        public Task <PowershellReturn> ExecuteAsync(
            string filename,
            string snapin,
            string module,
            IList <KeyValuePair <string, string> > parametersList,
            bool asJob)
        {
            if (string.IsNullOrWhiteSpace(filename))
            {
                throw new ArgumentException("Argument cannot be null, empty or composed of whitespaces only", "filename");
            }
            if (parametersList == null)
            {
                throw new ArgumentNullException("parametersList", "Argument cannot be null");
            }

            // Raise an event so we know what is going on
            try
            {
                var sb = new StringBuilder();

                foreach (KeyValuePair <string, string> kvp in parametersList)
                {
                    if (sb.Length > 0)
                    {
                        sb.Append(";");
                    }

                    sb.Append(string.Format("{0}:{1}", kvp.Key, kvp.Value));
                }

                DynamicPowershellApiEvents
                .Raise
                .ExecutingPowerShellScript(filename, sb.ToString());
            }
            catch (Exception)
            {
                DynamicPowershellApiEvents
                .Raise
                .ExecutingPowerShellScript(filename, "Unknown");
            }

            try
            {
                string strBaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
                string scriptContent    = File.ReadAllText(Path.Combine(strBaseDirectory, Path.Combine("ScriptRepository", filename)));

                RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();

                if (!String.IsNullOrWhiteSpace(snapin))
                {
                    PSSnapInException snapInException;
                    rsConfig.AddPSSnapIn(snapin, out snapInException);
                    if (snapInException != null)
                    {
                        DynamicPowershellApiEvents
                        .Raise
                        .SnapinException(snapInException.Message);
                        throw snapInException;
                    }
                }

                InitialSessionState initialSession = InitialSessionState.Create();
                if (!String.IsNullOrWhiteSpace(module))
                {
                    DynamicPowershellApiEvents
                    .Raise
                    .LoadingModule(module);
                    initialSession.ImportPSModule(new[] { module });
                }

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

                    powerShellInstance.AddScript(scriptContent);

                    foreach (var item in parametersList)
                    {
                        powerShellInstance.AddParameter(item.Key, item.Value);
                    }

                    // invoke execution on the pipeline (collecting output)
                    Collection <PSObject> psOutput = powerShellInstance.Invoke();

                    string sMessage = psOutput == null
                                                ? String.Empty
                                                : (
                        psOutput.LastOrDefault() != null
                                                        ? Regex.Replace(psOutput.LastOrDefault().ToString(), @"[^\u0000-\u007F]", string.Empty)
                                                                : String.Empty);

                    DynamicPowershellApiEvents.Raise.PowerShellScriptFinalised("The powershell has completed - anlaysing results now");

                    // check the other output streams (for example, the error stream)
                    if (powerShellInstance.HadErrors && powerShellInstance.Streams.Error.Count > 0)
                    {
                        var runtimeErrors = new List <PowerShellException>();

                        // Create a string builder for the errors
                        StringBuilder sb = new StringBuilder();

                        // error records were written to the error stream.
                        // do something with the items found.
                        sb.Append("PowerShell script raised errors:" + Environment.NewLine);
                        sb.Append(String.Format("{0}", sMessage));

                        var errors = powerShellInstance.Streams.Error.ReadAll();
                        if (errors != null)
                        {
                            foreach (var error in errors)
                            {
                                if (error.ErrorDetails == null)
                                {
                                    DynamicPowershellApiEvents.Raise.UnhandledException("error.ErrorDetails is null");
                                }

                                string errorDetails = error.ErrorDetails != null ? error.ErrorDetails.Message : String.Empty;
                                string scriptStack  = error.ScriptStackTrace ?? String.Empty;
                                string commandPath  = error.InvocationInfo.PSCommandPath ?? String.Empty;

                                if (error.ScriptStackTrace == null)
                                {
                                    DynamicPowershellApiEvents.Raise.UnhandledException("error.ScriptStackTrace is null");
                                }

                                if (error.InvocationInfo == null)
                                {
                                    DynamicPowershellApiEvents.Raise.UnhandledException("error.InvocationInfo is null");
                                }
                                else
                                {
                                    if (error.InvocationInfo.PSCommandPath == null)
                                    {
                                        DynamicPowershellApiEvents.Raise.UnhandledException("error.InvocationInfo.PSCommandPath is null");
                                    }
                                }

                                if (error.Exception == null)
                                {
                                    DynamicPowershellApiEvents.Raise.UnhandledException("error.Exception is null");
                                }

                                DynamicPowershellApiEvents.Raise.PowerShellError(
                                    errorDetails,
                                    scriptStack,
                                    commandPath,
                                    error.InvocationInfo.ScriptLineNumber);

                                runtimeErrors.Add(new PowerShellException
                                {
                                    StackTrace   = scriptStack,
                                    ErrorMessage = errorDetails,
                                    LineNumber   = error.InvocationInfo != null ? error.InvocationInfo.ScriptLineNumber : 0,
                                    ScriptName   = filename
                                });

                                if (error.Exception != null)
                                {
                                    sb.Append(String.Format("PowerShell Exception {0} : {1}", error.Exception.Message, error.Exception.StackTrace));
                                }

                                sb.Append(String.Format("Error {0}", error.ScriptStackTrace));
                            }
                        }
                        else
                        {
                            sb.Append(sMessage);
                        }

                        DynamicPowershellApiEvents.Raise.PowerShellScriptFinalised(String.Format("An error was rasied {0}", sb));

                        throw new PowerShellExecutionException(sb.ToString())
                              {
                                  Exceptions = runtimeErrors,
                                  LogTime    = DateTime.Now
                              };
                    }

                    var psGood = new PowershellReturn
                    {
                        PowerShellReturnedValidData = true,
                        ActualPowerShellData        = sMessage
                    };

                    DynamicPowershellApiEvents.Raise.PowerShellScriptFinalised(String.Format("The powershell returned the following {0}", psGood.ActualPowerShellData));

                    return(Task.FromResult(psGood));
                }
            }
            catch (Exception runnerException)
            {
                if (runnerException.GetType() == typeof(PowerShellExecutionException))
                {
                    throw;
                }

                DynamicPowershellApiEvents.Raise.UnhandledException(runnerException.Message, runnerException.StackTrace);
                throw new PowerShellExecutionException(runnerException.Message)
                      {
                          Exceptions = new List <PowerShellException>
                          {
                              new PowerShellException
                              {
                                  ErrorMessage = runnerException.Message,
                                  LineNumber   = 0,
                                  ScriptName   = "PowerShellRunner.cs",
                                  StackTrace   = runnerException.StackTrace
                              }
                          },
                          LogTime = DateTime.Now
                      };
            }
        }
Exemplo n.º 23
0
        private void loadCitrixCmdlets()
        {
            PSSnapInException psEx = null;

            //load all the citrix powershell snapins
            rsc.AddPSSnapIn("Citrix.ADIdentity.Admin.V2", out psEx);
            rsc.AddPSSnapIn("Citrix.Analytics.Admin.V1", out psEx);
            rsc.AddPSSnapIn("Citrix.AppLibrary.Admin.V1", out psEx);
            rsc.AddPSSnapIn("Citrix.AppV.Admin.V1", out psEx);
            rsc.AddPSSnapIn("Citrix.Broker.Admin.V2", out psEx);
            rsc.AddPSSnapIn("Citrix.Configuration.Admin.V2", out psEx);
            rsc.AddPSSnapIn("Citrix.ConfigurationLogging.Admin.V1", out psEx);
            rsc.AddPSSnapIn("Citrix.DelegatedAdmin.Admin.V1", out psEx);
            rsc.AddPSSnapIn("Citrix.EnvTest.Admin.V1", out psEx);
            rsc.AddPSSnapIn("Citrix.Host.Admin.V2", out psEx);
            rsc.AddPSSnapIn("Citrix.Licensing.Admin.V1", out psEx);
            rsc.AddPSSnapIn("Citrix.MachineCreation.Admin.V2", out psEx);
            rsc.AddPSSnapIn("Citrix.Monitor.Admin.V1", out psEx);
            rsc.AddPSSnapIn("Citrix.Orchestration.Admin.V1", out psEx);
            rsc.AddPSSnapIn("Citrix.Storefront.Admin.V1", out psEx);
            rsc.AddPSSnapIn("Citrix.Trust.Admin.V1", out psEx);
            rsc.AddPSSnapIn("Citrix.UserProfileManager.Admin.V1", out psEx);
        }