Beispiel #1
0
        public void Test_Transaction_Disposal_Clears_Streams_And_Commands()
        {
            // Arrange.
            using (var runspace = RunspaceFactory.CreateRunspace(InitialSessionState.Create()))
            {
                runspace.Open();
                using (var powershell = PowerShell.Create())
                    using (var tempDir = new TemporaryDirectory())
                    {
                        var transaction = new TestExecutionTransaction(powershell,
                                                                       Mock.Of <ILocationManager>(m =>
                                                                                                  m.OutputDirectory == tempDir.Directory &&
                                                                                                  m.ScriptLocation == tempDir.Directory));

                        powershell.Runspace = runspace;
                        powershell.Commands.AddCommand("Get-Host");
                        powershell.Commands.AddCommand("Get-Random");
                        powershell.Streams.Error.Add(new ErrorRecord(new InvalidOperationException(), "10", ErrorCategory.InvalidOperation, new object()));

                        // Act.
                        transaction.Dispose();

                        // Assert.
                        Assert.Empty(powershell.Commands.Commands);
                        Assert.Empty(powershell.Streams.Error);
                    }
            }
        }
Beispiel #2
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()
                }
                           ));
            }
        }
Beispiel #3
0
        public InvokeParallelTests()
        {
            var iss = InitialSessionState.Create();

            iss.LanguageMode = PSLanguageMode.FullLanguage;
            iss.Commands.Add(new []
            {
                new SessionStateCmdletEntry("Write-Error", typeof(WriteErrorCommand), null),
                new SessionStateCmdletEntry("Write-Verbose", typeof(WriteVerboseCommand), null),
                new SessionStateCmdletEntry("Write-Debug", typeof(WriteDebugCommand), null),
                new SessionStateCmdletEntry("Write-Progress", typeof(WriteProgressCommand), null),
                new SessionStateCmdletEntry("Write-Warning", typeof(WriteWarningCommand), null),
                new SessionStateCmdletEntry("Write-Information", typeof(WriteInformationCommand), null),
                new SessionStateCmdletEntry("Invoke-Parallel", typeof(InvokeParallelCommand), null),
            });
            iss.Providers.Add(new SessionStateProviderEntry("Function", typeof(FunctionProvider), null));
            iss.Providers.Add(new SessionStateProviderEntry("Variable", typeof(VariableProvider), null));
            iss.Variables.Add(new []
            {
                new SessionStateVariableEntry("ErrorActionPreference", ActionPreference.Continue, "Dictates the action taken when an error message is delivered"),
            });
            m_runspacePool = RunspaceFactory.CreateRunspacePool(iss);
            m_runspacePool.SetMaxRunspaces(10);
            m_runspacePool.Open();
        }
Beispiel #4
0
        private void ImportTestInvokeScriptCmdlet()
        {
            InitialSessionState sessionState = InitialSessionState.Create();
            string fileName = typeof(InvokeScriptTests).Assembly.Location;

            sessionState.ImportPSModule(new string[] { fileName });
            TestHost.InitialSessionState = sessionState;
        }
Beispiel #5
0
        public void LoadCmdletHelpers()
        {
            InitialSessionState sessionState = InitialSessionState.Create();
            string fileName = typeof(InitialSessionStateTests).Assembly.Location;

            sessionState.ImportPSModule(new string[] { fileName });
            TestHost.InitialSessionState = sessionState;
        }
        public static PowerShell CreateWithImportedModules(params string[] modules)
        {
            var sessionState = InitialSessionState.Create();

            sessionState.ExecutionPolicy = ExecutionPolicy.Unrestricted;
            sessionState.ImportPSModule(modules);
            return(PowerShell.Create(sessionState));
        }
Beispiel #7
0
        public void ImportPSModuleByFileNameAllowsCmdletInModuleToBeUsed()
        {
            InitialSessionState sessionState = InitialSessionState.Create();
            string fileName = typeof(InitialSessionStateTests).Assembly.Location;

            sessionState.ImportPSModule(new string[] { fileName });
            TestHost.InitialSessionState = sessionState;

            string output = TestHost.Execute("Invoke-Test -Parameter ParameterValue");

            Assert.AreEqual("Parameter='ParameterValue'" + Environment.NewLine, output);
        }
 InitialSessionState GetSessionState()
 {
     if (MyInvocation.BoundParameters.ContainsKey(nameof(InitialSessionState)))
     {
         if (InitialSessionState == null)
         {
             return(InitialSessionState.Create());
         }
         return(InitialSessionState);
     }
     return(GetSessionState(base.SessionState));
 }
        public void Cannot_run_standard_command_with_empty_session_state()
        {
            var sessionState = InitialSessionState.Create();

            using (var runspace = RunspaceFactory.CreateRunspace(sessionState))
                using (var psh = PowerShell.Create())
                {
                    psh.Runspace = runspace;
                    runspace.Open();
                    psh.AddCommand("Get-Location").Invoke();
                    Assert.Fail();
                }
        }
Beispiel #10
0
        public void VariableDefinedInInitialSessionStateCanBeUsedInStatement()
        {
            string variableValue             = "testVariableValue";
            var    variableEntry             = new SessionStateVariableEntry("testVariable", variableValue, "description");
            InitialSessionState sessionState = InitialSessionState.Create();

            sessionState.Variables.Add(variableEntry);
            TestHost.InitialSessionState = sessionState;

            string output = TestHost.Execute("$testVariable");

            Assert.AreEqual(variableValue + Environment.NewLine, output);
        }
 private object GetExpressionValue(ExpressionAst exprAst, bool isTrustedInput)
 {
     // be sure that there's a context at hand
     if (_context == null)
     {
         var rs = RunspaceFactory.CreateRunspace(InitialSessionState.Create());
         rs.Open();
         _context = rs.ExecutionContext;
     }
     if (!isTrustedInput) // if it's not trusted, call the safe value visitor
     {
         return(GetSafeValueVisitor.GetSafeValue(exprAst, _context, GetSafeValueVisitor.SafeValueContext.GetPowerShell));
     }
     return(Compiler.GetExpressionValue(exprAst, isTrustedInput, _context, _usingValueMap));
 }
Beispiel #12
0
        private object GetExpressionValue(ExpressionAst exprAst)
        {
            object obj2;

            if (IsConstantValueVisitor.IsConstant(exprAst, out obj2, false, false))
            {
                return(obj2);
            }
            if (this._context == null)
            {
                Runspace runspace = RunspaceFactory.CreateRunspace(InitialSessionState.Create());
                runspace.Open();
                this._context = runspace.ExecutionContext;
            }
            return(Compiler.GetExpressionValue(exprAst, this._context, this._usingValues));
        }
        private InitialSessionState CreateState(HostState context)
        {
            switch (context)
            {
            case HostState.None:
                return(InitialSessionState.Create());

            case HostState.Core:
                return(InitialSessionState.CreateDefault2());

            case HostState.Full:
                return(InitialSessionState.CreateDefault());

            default:
                throw new ArgumentException("Not a valid state");
            }
        }
Beispiel #14
0
        private static InitialSessionState CreateInitialSessionState()
        {
            var iss = InitialSessionState.Create();

            iss.LanguageMode = PSLanguageMode.FullLanguage;
            iss.Commands.Add(new[]
            {
                new SessionStateCmdletEntry("Write-Error", typeof(WriteErrorCommand), null),
                new SessionStateCmdletEntry("Write-Verbose", typeof(WriteVerboseCommand), null),
                new SessionStateCmdletEntry("Write-Debug", typeof(WriteDebugCommand), null),
                new SessionStateCmdletEntry("Write-Progress", typeof(WriteProgressCommand), null),
                new SessionStateCmdletEntry("Write-Warning", typeof(WriteWarningCommand), null),
                new SessionStateCmdletEntry("Write-Information", typeof(WriteInformationCommand), null),
                new SessionStateCmdletEntry("Invoke-Parallel", typeof(InvokeParallelCommand), null),
            });
            iss.Providers.Add(new SessionStateProviderEntry("Function", typeof(FunctionProvider), null));
            iss.Providers.Add(new SessionStateProviderEntry("Variable", typeof(VariableProvider), null));
            return(iss);
        }
        private static void TestScript(string script, Action <Collection <PSObject> > verify)
        {
            var sessionState = InitialSessionState.Create();

            sessionState.LanguageMode = PSLanguageMode.FullLanguage;
            sessionState.Commands.Add(new SessionStateCmdletEntry("Get-KnownFolder", typeof(GetKnownFolderCommand), null));
            using (var runspace = RunspaceFactory.CreateRunspace(sessionState))
                using (var psh = PowerShell.Create())
                {
                    psh.Runspace = runspace;
                    runspace.Open();
                    psh.AddScript(script);
                    var output = psh.Invoke();
                    if (psh.Streams.Error.Any())
                    {
                        Assert.Fail("Script execution failed, first error: {0}", psh.Streams.Error.First());
                    }

                    verify(output);
                }
        }
Beispiel #16
0
        public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo)
        {
            InitialSessionState state = null;
            bool        flag          = false;
            string      str           = TryGetValue(this.configHash, ConfigFileContants.SessionType);
            SessionType type          = SessionType.Default;
            bool        flag2         = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleCmdlets);
            bool        flag3         = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleFunctions);
            bool        flag4         = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleAliases);
            bool        flag5         = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleProviders);

            if (!string.IsNullOrEmpty(str))
            {
                type = (SessionType)Enum.Parse(typeof(SessionType), str, true);
                switch (type)
                {
                case SessionType.Empty:
                    state = InitialSessionState.Create();
                    goto Label_00AD;

                case SessionType.RestrictedRemoteServer:
                    state = InitialSessionState.CreateRestricted(SessionCapabilities.RemoteServer);
                    if (flag5)
                    {
                        InitialSessionState state2 = InitialSessionState.CreateDefault2();
                        state.Providers.Add(state2.Providers);
                    }
                    goto Label_00AD;
                }
                state = InitialSessionState.CreateDefault2();
            }
            else
            {
                state = InitialSessionState.CreateDefault2();
            }
Label_00AD:
            if (this.configHash.ContainsKey(ConfigFileContants.AssembliesToLoad))
            {
                string[] strArray = TryGetStringArray(this.configHash[ConfigFileContants.AssembliesToLoad]);
                if (strArray != null)
                {
                    foreach (string str2 in strArray)
                    {
                        state.Assemblies.Add(new SessionStateAssemblyEntry(str2));
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.ModulesToImport))
            {
                object[] objArray = TryGetObjectsOfType <object>(this.configHash[ConfigFileContants.ModulesToImport], new Type[] { typeof(string), typeof(Hashtable) });
                if ((this.configHash[ConfigFileContants.ModulesToImport] != null) && (objArray == null))
                {
                    PSInvalidOperationException exception = new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArray, ConfigFileContants.ModulesToImport));
                    exception.SetErrorId("InvalidModulesToImportKeyEntries");
                    throw exception;
                }
                if (objArray != null)
                {
                    Collection <ModuleSpecification> modules = new Collection <ModuleSpecification>();
                    foreach (object obj2 in objArray)
                    {
                        ModuleSpecification item = null;
                        string str4 = obj2 as string;
                        if (!string.IsNullOrEmpty(str4))
                        {
                            item = new ModuleSpecification(str4);
                        }
                        else
                        {
                            Hashtable moduleSpecification = obj2 as Hashtable;
                            if (moduleSpecification != null)
                            {
                                item = new ModuleSpecification(moduleSpecification);
                            }
                        }
                        if (item != null)
                        {
                            if (string.Equals(InitialSessionState.CoreModule, item.Name, StringComparison.OrdinalIgnoreCase))
                            {
                                if (type == SessionType.Empty)
                                {
                                    state.ImportCorePSSnapIn();
                                }
                            }
                            else
                            {
                                modules.Add(item);
                            }
                        }
                    }
                    state.ImportPSModule(modules);
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.AliasDefinitions))
            {
                Hashtable[] hashtableArray = TryGetHashtableArray(this.configHash[ConfigFileContants.AliasDefinitions]);
                if (hashtableArray != null)
                {
                    foreach (Hashtable hashtable2 in hashtableArray)
                    {
                        SessionStateAliasEntry entry = this.CreateSessionStateAliasEntry(hashtable2);
                        if (entry != null)
                        {
                            state.Commands.Add(entry);
                        }
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.FunctionDefinitions))
            {
                Hashtable[] hashtableArray2 = TryGetHashtableArray(this.configHash[ConfigFileContants.FunctionDefinitions]);
                if (hashtableArray2 != null)
                {
                    foreach (Hashtable hashtable3 in hashtableArray2)
                    {
                        SessionStateFunctionEntry entry2 = this.CreateSessionStateFunctionEntry(hashtable3);
                        if (entry2 != null)
                        {
                            state.Commands.Add(entry2);
                        }
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.VariableDefinitions))
            {
                Hashtable[] hashtableArray3 = TryGetHashtableArray(this.configHash[ConfigFileContants.VariableDefinitions]);
                if (hashtableArray3 != null)
                {
                    foreach (Hashtable hashtable4 in hashtableArray3)
                    {
                        if (!hashtable4.ContainsKey(ConfigFileContants.VariableValueToken) || !(hashtable4[ConfigFileContants.VariableValueToken] is ScriptBlock))
                        {
                            SessionStateVariableEntry entry3 = this.CreateSessionStateVariableEntry(hashtable4);
                            if (entry3 != null)
                            {
                                state.Variables.Add(entry3);
                            }
                        }
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.TypesToProcess))
            {
                string[] strArray2 = TryGetStringArray(this.configHash[ConfigFileContants.TypesToProcess]);
                if (strArray2 != null)
                {
                    foreach (string str5 in strArray2)
                    {
                        if (!string.IsNullOrEmpty(str5))
                        {
                            state.Types.Add(new SessionStateTypeEntry(str5));
                        }
                    }
                }
            }
            if (this.configHash.ContainsKey(ConfigFileContants.FormatsToProcess))
            {
                string[] strArray3 = TryGetStringArray(this.configHash[ConfigFileContants.FormatsToProcess]);
                if (strArray3 != null)
                {
                    foreach (string str6 in strArray3)
                    {
                        if (!string.IsNullOrEmpty(str6))
                        {
                            state.Formats.Add(new SessionStateFormatEntry(str6));
                        }
                    }
                }
            }
            if ((flag2 || flag3) || (flag4 || flag5))
            {
                flag = true;
            }
            if (flag)
            {
                state.Variables.Add(new SessionStateVariableEntry("PSModuleAutoLoadingPreference", PSModuleAutoLoadingPreference.None, string.Empty, ScopedItemOptions.None));
                if (type == SessionType.Default)
                {
                    state.ImportPSCoreModule(InitialSessionState.EngineModules.ToArray <string>());
                }
                if (!flag2)
                {
                    state.Commands.Remove("Import-Module", typeof(SessionStateCmdletEntry));
                }
                if (!flag4)
                {
                    state.Commands.Remove("ipmo", typeof(SessionStateAliasEntry));
                }
            }
            return(state);
        }
Beispiel #17
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
                      };
            }
        }
Beispiel #18
0
 private void AddPSSnapIns(Collection <string> snapInList)
 {
     if (snapInList != null)
     {
         if (base.Context.RunspaceConfiguration == null)
         {
             Collection <PSSnapInInfo> snapIns = base.GetSnapIns(null);
             InitialSessionState       state   = InitialSessionState.Create();
             bool flag = false;
             foreach (string str in snapInList)
             {
                 if (InitialSessionState.IsEngineModule(str))
                 {
                     base.WriteNonTerminatingError(str, "LoadSystemSnapinAsModule", PSTraceSource.NewArgumentException(str, "MshSnapInCmdletResources", "LoadSystemSnapinAsModule", new object[] { str }), ErrorCategory.InvalidArgument);
                 }
                 else
                 {
                     try
                     {
                         PSSnapInInfo psSnapInInfo = PSSnapInReader.Read(Utils.GetCurrentMajorVersion(), str);
                         PSSnapInInfo info2        = PSSnapInCommandBase.IsSnapInLoaded(snapIns, psSnapInInfo);
                         if (info2 == null)
                         {
                             PSSnapInException exception;
                             info2 = state.ImportPSSnapIn(str, out exception);
                             flag  = true;
                             base.Context.InitialSessionState.ImportedSnapins.Add(info2.Name, info2);
                         }
                         if (this._passThru)
                         {
                             info2.LoadIndirectResources(base.ResourceReader);
                             base.WriteObject(info2);
                         }
                     }
                     catch (PSSnapInException exception2)
                     {
                         base.WriteNonTerminatingError(str, "AddPSSnapInRead", exception2, ErrorCategory.InvalidData);
                     }
                 }
             }
             if (flag)
             {
                 state.Bind(base.Context, true);
             }
         }
         else
         {
             foreach (string str2 in snapInList)
             {
                 Exception innerException = null;
                 try
                 {
                     PSSnapInException warning        = null;
                     PSSnapInInfo      sendToPipeline = base.Runspace.AddPSSnapIn(str2, out warning);
                     if (warning != null)
                     {
                         base.WriteNonTerminatingError(str2, "AddPSSnapInRead", warning, ErrorCategory.InvalidData);
                     }
                     if (this._passThru)
                     {
                         sendToPipeline.LoadIndirectResources(base.ResourceReader);
                         base.WriteObject(sendToPipeline);
                     }
                 }
                 catch (PSArgumentException exception5)
                 {
                     innerException = exception5;
                 }
                 catch (PSSnapInException exception6)
                 {
                     innerException = exception6;
                 }
                 catch (SecurityException exception7)
                 {
                     innerException = exception7;
                 }
                 if (innerException != null)
                 {
                     base.WriteNonTerminatingError(str2, "AddPSSnapInRead", innerException, ErrorCategory.InvalidArgument);
                 }
             }
         }
     }
 }
 protected override void ProcessRecord()
 {
     foreach (string str in this._pssnapins)
     {
         Collection <PSSnapInInfo> snapIns = base.GetSnapIns(str);
         if (snapIns.Count == 0)
         {
             base.WriteNonTerminatingError(str, "NoPSSnapInsFound", PSTraceSource.NewArgumentException(str, "MshSnapInCmdletResources", "NoPSSnapInsFound", new object[] { str }), ErrorCategory.InvalidArgument);
         }
         else
         {
             foreach (PSSnapInInfo info in snapIns)
             {
                 if (base.ShouldProcess(info.Name))
                 {
                     Exception innerException = null;
                     if ((base.Runspace == null) && (base.Context.InitialSessionState != null))
                     {
                         try
                         {
                             PSSnapInException exception2;
                             PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(info.Name);
                             if (MshConsoleInfo.IsDefaultPSSnapIn(info.Name, base.Context.InitialSessionState.defaultSnapins))
                             {
                                 throw PSTraceSource.NewArgumentException(info.Name, "ConsoleInfoErrorStrings", "CannotRemoveDefault", new object[] { info.Name });
                             }
                             InitialSessionState state = InitialSessionState.Create();
                             state.ImportPSSnapIn(info, out exception2);
                             state.Unbind(base.Context);
                             base.Context.InitialSessionState.ImportedSnapins.Remove(info.Name);
                         }
                         catch (PSArgumentException exception3)
                         {
                             innerException = exception3;
                         }
                         if (innerException != null)
                         {
                             base.WriteNonTerminatingError(str, "RemovePSSnapIn", innerException, ErrorCategory.InvalidArgument);
                         }
                     }
                     else
                     {
                         try
                         {
                             PSSnapInException warning        = null;
                             PSSnapInInfo      sendToPipeline = base.Runspace.RemovePSSnapIn(info.Name, out warning);
                             if (warning != null)
                             {
                                 base.WriteNonTerminatingError(info.Name, "RemovePSSnapInRead", warning, ErrorCategory.InvalidData);
                             }
                             if (this._passThru)
                             {
                                 sendToPipeline.LoadIndirectResources(base.ResourceReader);
                                 base.WriteObject(sendToPipeline);
                             }
                         }
                         catch (PSArgumentException exception5)
                         {
                             innerException = exception5;
                         }
                         if (innerException != null)
                         {
                             base.WriteNonTerminatingError(str, "RemovePSSnapIn", innerException, ErrorCategory.InvalidArgument);
                         }
                     }
                 }
             }
         }
     }
 }
        /// <summary>
        /// Adds one or more snapins
        /// </summary>
        /// <param name="snapInList">List of snapin IDs</param>
        /// <remarks>
        /// This is a helper method and should not throw any
        /// exceptions. All exceptions are caught and displayed
        /// to the user using write* methods
        /// </remarks>
        private void AddPSSnapIns(Collection <string> snapInList)
        {
            if (snapInList == null)
            {
                // nothing to add
                return;
            }

            //BUGBUG TODO - brucepay - this is a workaround for not being able to dynamically update
            // the set of cmdlets in a runspace if there is no RunspaceConfiguration object.
            // This is a temporary fix to unblock remoting tests and need to be corrected/completed
            // before we can ship...

            // If there is no RunspaceConfig object, then
            // use an InitialSessionState object to gather and
            // bind the cmdlets from the snapins...
            if (Context.RunspaceConfiguration == null)
            {
                Collection <PSSnapInInfo> loadedSnapins = base.GetSnapIns(null);
                InitialSessionState       iss           = InitialSessionState.Create();
                bool isAtleastOneSnapinLoaded           = false;
                foreach (string snapIn in snapInList)
                {
                    if (InitialSessionState.IsEngineModule(snapIn))
                    {
                        WriteNonTerminatingError(snapIn, "LoadSystemSnapinAsModule",
                                                 PSTraceSource.NewArgumentException(snapIn,
                                                                                    MshSnapInCmdletResources.LoadSystemSnapinAsModule, snapIn),
                                                 ErrorCategory.InvalidArgument);
                    }
                    else
                    {
                        PSSnapInException warning;
                        try
                        {
                            // Read snapin data
                            PSSnapInInfo newPSSnapIn  = PSSnapInReader.Read(Utils.GetCurrentMajorVersion(), snapIn);
                            PSSnapInInfo psSnapInInfo = IsSnapInLoaded(loadedSnapins, newPSSnapIn);

                            // that means snapin is not already loaded ..so load the snapin
                            // now.
                            if (null == psSnapInInfo)
                            {
                                psSnapInInfo             = iss.ImportPSSnapIn(snapIn, out warning);
                                isAtleastOneSnapinLoaded = true;
                                Context.InitialSessionState.ImportedSnapins.Add(psSnapInInfo.Name, psSnapInInfo);
                            }
                            // Write psSnapInInfo object only if passthru is specified.
                            if (_passThru)
                            {
                                // Load the pssnapin info properties that are localizable and redirected in the registry
                                psSnapInInfo.LoadIndirectResources(ResourceReader);
                                WriteObject(psSnapInInfo);
                            }
                        }

                        catch (PSSnapInException pse)
                        {
                            WriteNonTerminatingError(snapIn, "AddPSSnapInRead", pse, ErrorCategory.InvalidData);
                        }
                    }
                }

                if (isAtleastOneSnapinLoaded)
                {
                    // Now update the session state with the new stuff...
                    iss.Bind(Context, /*updateOnly*/ true);
                }

                return;
            }

            foreach (string psSnapIn in snapInList)
            {
                Exception exception = null;

                try
                {
                    PSSnapInException warning = null;

                    PSSnapInInfo psSnapInInfo = this.Runspace.AddPSSnapIn(psSnapIn, out warning);

                    if (warning != null)
                    {
                        WriteNonTerminatingError(psSnapIn, "AddPSSnapInRead", warning, ErrorCategory.InvalidData);
                    }

                    // Write psSnapInInfo object only if passthru is specified.
                    if (_passThru)
                    {
                        // Load the pssnapin info properties that are localizable and redirected in the registry
                        psSnapInInfo.LoadIndirectResources(ResourceReader);
                        WriteObject(psSnapInInfo);
                    }
                }
                catch (PSArgumentException ae)
                {
                    exception = ae;
                }
                catch (PSSnapInException sle)
                {
                    exception = sle;
                }
                catch (System.Security.SecurityException se)
                {
                    exception = se;
                }

                if (exception != null)
                {
                    WriteNonTerminatingError(psSnapIn,
                                             "AddPSSnapInRead",
                                             exception,
                                             ErrorCategory.InvalidArgument);
                }
            }
        }
        /// <summary>
        /// Removes pssnapins from the current console file.
        /// </summary>
        /// <remarks>
        /// The pssnapin is not unloaded from the current engine. So all the cmdlets that are
        /// represented by this pssnapin will continue to work.
        /// </remarks>
        protected override void ProcessRecord()
        {
            foreach (string psSnapIn in _pssnapins)
            {
                Collection <PSSnapInInfo> snapIns = GetSnapIns(psSnapIn);

                // snapIns won't be null..
                Diagnostics.Assert(snapIns != null, "GetSnapIns() returned null");
                if (snapIns.Count == 0)
                {
                    WriteNonTerminatingError(psSnapIn, "NoPSSnapInsFound",
                                             PSTraceSource.NewArgumentException(psSnapIn,
                                                                                MshSnapInCmdletResources.NoPSSnapInsFound, psSnapIn),
                                             ErrorCategory.InvalidArgument);

                    continue;
                }

                foreach (PSSnapInInfo snapIn in snapIns)
                {
                    // confirm the operation first
                    // this is always false if WhatIf is set
                    if (ShouldProcess(snapIn.Name))
                    {
                        Exception exception = null;

                        if (this.Runspace == null && this.Context.InitialSessionState != null)
                        {
                            try
                            {
                                // Check if this snapin can be removed

                                // Monad has specific restrictions on the mshsnapinid like
                                // mshsnapinid should be A-Za-z0-9.-_ etc.
                                PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(snapIn.Name);

                                if (MshConsoleInfo.IsDefaultPSSnapIn(snapIn.Name, this.Context.InitialSessionState.defaultSnapins))
                                {
                                    throw PSTraceSource.NewArgumentException(snapIn.Name, ConsoleInfoErrorStrings.CannotRemoveDefault, snapIn.Name);
                                }

                                // Handle the initial session state case...
                                InitialSessionState iss = InitialSessionState.Create();
                                PSSnapInException   warning;

                                // Get the snapin information...
                                iss.ImportPSSnapIn(snapIn, out warning);
                                iss.Unbind(Context);
                                Context.InitialSessionState.ImportedSnapins.Remove(snapIn.Name);
                            }
                            catch (PSArgumentException ae)
                            {
                                exception = ae;
                            }

                            if (exception != null)
                            {
                                WriteNonTerminatingError(psSnapIn, "RemovePSSnapIn", exception, ErrorCategory.InvalidArgument);
                            }
                        }
                        else
                        {
                            try
                            {
                                PSSnapInException warning = null;

                                PSSnapInInfo psSnapInInfo = this.Runspace.RemovePSSnapIn(snapIn.Name, out warning);

                                if (warning != null)
                                {
                                    WriteNonTerminatingError(snapIn.Name, "RemovePSSnapInRead", warning, ErrorCategory.InvalidData);
                                }

                                if (_passThru)
                                {
                                    // Load the pssnapin info properties that are localizable and redirected in the registry
                                    psSnapInInfo.LoadIndirectResources(ResourceReader);
                                    WriteObject(psSnapInInfo);
                                }
                            }
                            catch (PSArgumentException ae)
                            {
                                exception = ae;
                            }

                            if (exception != null)
                            {
                                WriteNonTerminatingError(psSnapIn, "RemovePSSnapIn", exception, ErrorCategory.InvalidArgument);
                            }
                        }
                    } // ShouldContinue
                }
            }
        }
        private static List <string> GetSingleAstRequiredModules(Ast ast, Token[] tokens)
        {
            List <string> modules   = new List <string>();
            List <string> resources = new List <string>();
            var           imports   = tokens.Where(token =>
                                                   String.Compare(token.Text, "Import-DscResource", StringComparison.OrdinalIgnoreCase) == 0);

            //
            // Create a function with the same name as Import-DscResource keyword and use powershell
            // argument function binding to emulate Import-DscResource argument binding.
            //
            InitialSessionState       initialSessionState            = InitialSessionState.Create();
            SessionStateFunctionEntry importDscResourcefunctionEntry = new SessionStateFunctionEntry(
                "Import-DscResource", @"param($Name, $ModuleName)
                if ($ModuleName) 
                {
                    foreach ($m in $ModuleName) { $global:modules.Add($m) }
                } else {
                    foreach ($n in $Name) { $global:resources.Add($n) }
                }
            ");

            initialSessionState.Commands.Add(importDscResourcefunctionEntry);
            initialSessionState.LanguageMode = PSLanguageMode.RestrictedLanguage;
            var moduleVarEntry    = new SessionStateVariableEntry("modules", modules, "");
            var resourcesVarEntry = new SessionStateVariableEntry("resources", resources, "");

            initialSessionState.Variables.Add(moduleVarEntry);
            initialSessionState.Variables.Add(resourcesVarEntry);

            using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create(initialSessionState))
            {
                foreach (var import in imports)
                {
                    int startOffset      = import.Extent.StartOffset;
                    var asts             = ast.FindAll(a => IsCandidateForImportDscResourceAst(a, startOffset), true);
                    int longestLen       = -1;
                    Ast longestCandidate = null;
                    foreach (var candidatAst in asts)
                    {
                        int curLen = candidatAst.Extent.EndOffset - candidatAst.Extent.StartOffset;
                        if (curLen > longestLen)
                        {
                            longestCandidate = candidatAst;
                            longestLen       = curLen;
                        }
                    }
                    // longestCandidate should contain AST for import-dscresource, like "Import-DSCResource -Module x -Name y".
                    if (longestCandidate != null)
                    {
                        string importText = longestCandidate.Extent.Text;
                        // We invoke-command "importText" here. Script injection is prevented:
                        // We checked that file represents a valid AST without errors.
                        powerShell.AddScript(importText);
                        powerShell.Invoke();
                        powerShell.Commands.Clear();
                    }
                }
            }
            modules.AddRange(resources.Select(GetModuleNameForDscResource));
            return(modules);
        }
        /// <summary>
        /// Run some commands to demonstrate the script capabilities.
        /// </summary>
        private void RunCommands()
        {
            this.runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault());
            this.runspace.Open();
            this.RunScript("$a=0;$a", "Assigning to a variable will work for a default InitialSessionState");
            this.runspace.Close();

            this.runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault());
            this.runspace.InitialSessionState.LanguageMode = PSLanguageMode.RestrictedLanguage;
            this.runspace.Open();
            this.RunScript("$a=0;$a", "Assigning to a variable will not work in RestrictedLanguage LanguageMode");
            this.runspace.Close();

            this.runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault());
            this.runspace.InitialSessionState.LanguageMode = PSLanguageMode.NoLanguage;
            this.runspace.Open();
            this.RunScript("10/2", "A script will not work in NoLanguage LanguageMode");
            this.runspace.Close();

            this.runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault());
            this.runspace.Open();
            string scriptComment = "get-childitem with a default InitialSessionState will work since the standard \n" +
                                   "PowerShell cmdlets are included in the default InitialSessionState";

            this.RunScript("get-childitem", scriptComment);
            this.runspace.Close();

            InitialSessionState defaultSessionState = InitialSessionState.CreateDefault();

            defaultSessionState.Commands.Add(new SessionStateAliasEntry("dir2", "get-childitem"));
            this.runspace = RunspaceFactory.CreateRunspace(defaultSessionState);
            this.runspace.Open();
            this.RunScript("dir2", "An alias, like dir2, can be added to InitialSessionState");
            this.runspace.Close();

            defaultSessionState = InitialSessionState.CreateDefault();
            int commandIndex = GetIndexOfEntry(defaultSessionState.Commands, "get-childitem");

            defaultSessionState.Commands.RemoveItem(commandIndex);
            this.runspace = RunspaceFactory.CreateRunspace(defaultSessionState);
            this.runspace.Open();
            scriptComment = "get-childitem was removed from the list of commands so it\nwill no longer be found";
            this.RunScript("get-childitem", scriptComment);
            this.runspace.Close();

            defaultSessionState = InitialSessionState.CreateDefault();
            defaultSessionState.Providers.Clear();
            this.runspace = RunspaceFactory.CreateRunspace(defaultSessionState);
            this.runspace.Open();
            this.RunScript("get-childitem", "There are no providers so get-childitem will not work");
            this.runspace.Close();

            // Marks a command as private, and then defines a proxy command
            // that uses the private command.  One reason to define a proxy for a command is
            // to remove a parameter of the original command.
            // For a more complete sample of a proxy command, see the Runspace11 sample.
            defaultSessionState = InitialSessionState.CreateDefault();
            commandIndex        = GetIndexOfEntry(defaultSessionState.Commands, "get-childitem");
            defaultSessionState.Commands[commandIndex].Visibility = SessionStateEntryVisibility.Private;
            CommandMetadata getChildItemMetadata = new CommandMetadata(
                typeof(Microsoft.PowerShell.Commands.GetChildItemCommand));

            getChildItemMetadata.Parameters.Remove("Recurse");
            string getChildItemBody = ProxyCommand.Create(getChildItemMetadata);

            defaultSessionState.Commands.Add(new SessionStateFunctionEntry("get-childitem2", getChildItemBody));
            this.runspace = RunspaceFactory.CreateRunspace(defaultSessionState);
            this.runspace.Open();
            this.RunScript("get-childitem", "get-childitem is private so it will not be available");
            scriptComment = "get-childitem2 is is a proxy to get-childitem. \n" +
                            "It works even when get-childitem is private.";
            this.RunScript("get-childitem2", scriptComment);
            scriptComment = "This will fail. Unlike get-childitem, get-childitem2 does not have -Recurse";
            this.RunScript("get-childitem2 -Recurse", scriptComment);

            InitialSessionState cleanSessionState = InitialSessionState.Create();

            this.runspace = RunspaceFactory.CreateRunspace(cleanSessionState);
            this.runspace.Open();
            scriptComment = "A script will not work because \n" +
                            "InitialSessionState.Create() will have the default LanguageMode of NoLanguage";
            this.RunScript("10/2", scriptComment);
            this.runspace.Close();

            cleanSessionState = InitialSessionState.Create();
            cleanSessionState.LanguageMode = PSLanguageMode.FullLanguage;
            this.runspace = RunspaceFactory.CreateRunspace(cleanSessionState);
            this.runspace.Open();
            scriptComment = "get-childitem, standard cmdlets and providers are not present \n" +
                            "in an InitialSessionState returned from InitialSessionState.Create()";
            this.RunScript("get-childitem", scriptComment);
            this.runspace.Close();

            cleanSessionState = InitialSessionState.Create();
            cleanSessionState.Commands.Add(
                new SessionStateCmdletEntry(
                    "Get-ChildItem",
                    typeof(Microsoft.PowerShell.Commands.GetChildItemCommand),
                    null));
            cleanSessionState.Providers.Add(
                new SessionStateProviderEntry(
                    "FileSystem",
                    typeof(Microsoft.PowerShell.Commands.FileSystemProvider),
                    null));
            cleanSessionState.LanguageMode = PSLanguageMode.FullLanguage;
            this.runspace = RunspaceFactory.CreateRunspace(cleanSessionState);
            this.runspace.Open();
            scriptComment = "get-childitem and the FileSystem provider were explicitly added\n" +
                            "so get-childitem will work";
            this.RunScript("get-childitem", scriptComment);
            this.runspace.Close();

            Console.Write("Done...");
            Console.ReadLine();
        }