Ejemplo n.º 1
0
 /// <summary>
 /// Handle internal Pool RunspaceCreated events.
 /// </summary>
 /// <param name="source"></param>
 /// <param name="args"></param>
 private void OnRunspaceCreated(object source, RunspaceCreatedEventArgs args)
 {
     // call any event handlers on this, replacing the
     // internalPool sender with 'this' since receivers
     // are expecting a RunspacePool
     InternalRunspaceCreated.SafeInvoke(this, args);
 }
Ejemplo n.º 2
0
 private void OnRunspaceCreated(object source, RunspaceCreatedEventArgs args)
 {
     if (this.InternalRunspaceCreated == null)
     {
         return;
     }
     this.InternalRunspaceCreated((object)this, args);
 }
Ejemplo n.º 3
0
        private void InvokeStartupScripts(RunspaceCreatedEventArgs args)
        {
            Command cmdToRun = null;
            if (!string.IsNullOrEmpty(_configData.StartupScript))
            {
                // build the startup script..merge output / error.
                cmdToRun = new Command(_configData.StartupScript, false, false);
            }
            else if (!string.IsNullOrEmpty(_configData.InitializationScriptForOutOfProcessRunspace))
            {
                cmdToRun = new Command(_configData.InitializationScriptForOutOfProcessRunspace, true, false);
            }

            if (null != cmdToRun)
            {
                InvokeScript(cmdToRun, args);

                // if startup script set $PSApplicationPrivateData, then use that value as ApplicationPrivateData
                // instead of using results from PSSessionConfiguration.GetApplicationPrivateData()
                if (RunspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opening)
                {
                    object privateDataVariable = args.Runspace.SessionStateProxy.PSVariable.GetValue("global:PSApplicationPrivateData");
                    if (privateDataVariable != null)
                    {
                        _applicationPrivateData = (PSPrimitiveDictionary)LanguagePrimitives.ConvertTo(
                            privateDataVariable,
                            typeof(PSPrimitiveDictionary),
                            true,
                            CultureInfo.InvariantCulture,
                            null);
                    }
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Raised by RunspacePool whenever a new runspace is created. This is used
        /// by the driver to run startup script as well as set personal folder
        /// as the current working directory.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args">
        /// Runspace that was created by the RunspacePool.
        /// </param>
        private void HandleRunspaceCreated(object sender, RunspaceCreatedEventArgs args)
        {
            this.ServerRemoteHost.Runspace = args.Runspace;

            // If the system lockdown policy says "Enforce", do so (unless it's in the
            // more restrictive NoLanguage mode)
            if ((SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) &&
                (args.Runspace.ExecutionContext.LanguageMode != PSLanguageMode.NoLanguage))
            {
                args.Runspace.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage;
            }

            // Set the current location to MyDocuments folder for this runspace.
            // This used to be set to the Personal folder but was changed to MyDocuments folder for 
            // compatibility with PowerShell on Nano Server for PowerShell V5.
            // This is needed because in the remoting scenario, Environment.CurrentDirectory
            // always points to System Folder (%windir%\system32) irrespective of the
            // user as %HOMEDRIVE% and %HOMEPATH% are not available for the logon process.
            // Doing this here than AutomationEngine as I dont want to introduce a dependency
            // on Remoting in PowerShell engine
            try
            {
                string personalfolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                args.Runspace.ExecutionContext.EngineSessionState.SetLocation(personalfolder);
            }
            catch (Exception e)
            {
                // SetLocation API can call 3rd party code and so there is no telling what exception may be thrown.
                // Setting location is not critical and is expected not to work with some account types, so we want
                // to ignore all but critical errors.
                CommandProcessorBase.CheckForSevereException(e);
            }

            // Run startup scripts
            InvokeStartupScripts(args);

            // Now that the server side runspace is set up allow the secondary handler to run.
            HandleRunspaceCreatedForTypeTable(sender, args);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Invokes a PowerShell instance 
        /// </summary>
        /// <param name="powershell"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        private PSDataCollection<PSObject> InvokePowerShell(PowerShell powershell, RunspaceCreatedEventArgs args)
        {
            Debug.Assert(powershell != null, "powershell shouldn't be null");

            // run the startup script on the runspace's host
            HostInfo hostInfo = _remoteHost.HostInfo;
            ServerPowerShellDriver driver = new ServerPowerShellDriver(
                powershell,
                null,
                true,
                Guid.Empty,
                this.InstanceId,
                this,
#if !CORECLR // No ApartmentState In CoreCLR
                args.Runspace.ApartmentState,
#endif                
                hostInfo,
                RemoteStreamOptions.AddInvocationInfo,
                false,
                args.Runspace);

            IAsyncResult asyncResult = driver.Start();

            // if there was an exception running the script..this may throw..this will
            // result in the runspace getting closed/broken.
            PSDataCollection<PSObject> results = powershell.EndInvoke(asyncResult);

            // find out if there are any error records reported. If there is one, report the error..
            // this will result in the runspace getting closed/broken.
            ArrayList errorList = (ArrayList)powershell.Runspace.GetExecutionContext.DollarErrorVariable;
            if (errorList.Count > 0)
            {
                string exceptionThrown;
                ErrorRecord lastErrorRecord = errorList[0] as ErrorRecord;
                if (lastErrorRecord != null)
                {
                    exceptionThrown = lastErrorRecord.ToString();
                }
                else
                {
                    Exception lastException = errorList[0] as Exception;
                    if (lastException != null)
                    {
                        exceptionThrown = (lastException.Message != null) ? lastException.Message : string.Empty;
                    }
                    else
                    {
                        exceptionThrown = string.Empty;
                    }
                }

                throw PSTraceSource.NewInvalidOperationException(RemotingErrorIdStrings.StartupScriptThrewTerminatingError, exceptionThrown);
            }

            return results;
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Invokes a script
        /// </summary>
        /// <param name="cmdToRun"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        private PSDataCollection<PSObject> InvokeScript(Command cmdToRun, RunspaceCreatedEventArgs args)
        {
            Debug.Assert(cmdToRun != null, "cmdToRun shouldn't be null");

            cmdToRun.CommandOrigin = CommandOrigin.Internal;
            cmdToRun.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
            PowerShell powershell = PowerShell.Create();
            powershell.AddCommand(cmdToRun).AddCommand("out-default");

            return InvokePowerShell(powershell, args);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// RunspaceCreated eventhandler. This is used to set TypeTable for TransportManager.
        /// TransportManager needs TypeTable for Serializing/Deserializing objects.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void HandleRunspaceCreatedForTypeTable(object sender, RunspaceCreatedEventArgs args)
        {
            DataStructureHandler.TypeTable = args.Runspace.ExecutionContext.TypeTable;
            _rsToUseForSteppablePipeline = args.Runspace;

            SetupRemoteDebugger(_rsToUseForSteppablePipeline);

            if (!string.IsNullOrEmpty(_configurationName))
            {
                // Client is requesting a configured session.  
                // Create a configured remote runspace and push onto host stack.
                if ((_remoteHost != null) && !(_remoteHost.IsRunspacePushed))
                {
                    // Let exceptions propagate.
                    RemoteRunspace remoteRunspace = HostUtilities.CreateConfiguredRunspace(_configurationName, _remoteHost);

                    _remoteHost.AllowPushRunspace = true;
                    _remoteHost.PropagatePop = true;

                    _remoteHost.PushRunspace(remoteRunspace);
                }
            }
        }
Ejemplo n.º 8
0
 private void OnRunspaceCreated(object source, RunspaceCreatedEventArgs args)
 {
     this.InternalRunspaceCreated.SafeInvoke<RunspaceCreatedEventArgs>(this, args);
 }
Ejemplo n.º 9
0
 private void OnRunspaceCreated(object source, RunspaceCreatedEventArgs args)
 {
     this.InternalRunspaceCreated.SafeInvoke <RunspaceCreatedEventArgs>(this, args);
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Handle internal Pool RunspaceCreated events.
 /// </summary>
 /// <param name="source"></param>
 /// <param name="args"></param>
 private void OnRunspaceCreated(object source, RunspaceCreatedEventArgs args)
 {
     // call any event handlers on this, replacing the 
     // internalPool sender with 'this' since receivers
     // are expecting a RunspacePool
     InternalRunspaceCreated.SafeInvoke(this, args);
 }
Ejemplo n.º 11
0
 private PSDataCollection<PSObject> InvokeScript(Command cmdToRun, RunspaceCreatedEventArgs args)
 {
     cmdToRun.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
     PowerShell powershell = PowerShell.Create();
     powershell.AddCommand(cmdToRun).AddCommand("out-default");
     return this.InvokePowerShell(powershell, args);
 }
Ejemplo n.º 12
0
 private PSDataCollection<PSObject> InvokePowerShell(PowerShell powershell, RunspaceCreatedEventArgs args)
 {
     string str;
     HostInfo hostInfo = this.remoteHost.HostInfo;
     IAsyncResult asyncResult = new ServerPowerShellDriver(powershell, null, true, Guid.Empty, this.InstanceId, this, args.Runspace.ApartmentState, hostInfo, RemoteStreamOptions.AddInvocationInfo, false, args.Runspace).Start();
     PSDataCollection<PSObject> datas = powershell.EndInvoke(asyncResult);
     ArrayList dollarErrorVariable = (ArrayList) powershell.Runspace.GetExecutionContext.DollarErrorVariable;
     if (dollarErrorVariable.Count <= 0)
     {
         return datas;
     }
     ErrorRecord record = dollarErrorVariable[0] as ErrorRecord;
     if (record != null)
     {
         str = record.ToString();
     }
     else
     {
         Exception exception = dollarErrorVariable[0] as Exception;
         if (exception != null)
         {
             str = (exception.Message != null) ? exception.Message : string.Empty;
         }
         else
         {
             str = string.Empty;
         }
     }
     throw PSTraceSource.NewInvalidOperationException("RemotingErrorIdStrings", PSRemotingErrorId.StartupScriptThrewTerminatingError.ToString(), new object[] { str });
 }
Ejemplo n.º 13
0
 private void HandleRunspaceCreatedForTypeTable(object sender, RunspaceCreatedEventArgs args)
 {
     this.dsHandler.TypeTable = args.Runspace.ExecutionContext.TypeTable;
     this.localRunspacePool.RunspaceCreated -= new EventHandler<RunspaceCreatedEventArgs>(this.HandleRunspaceCreatedForTypeTable);
     this.rsToUseForSteppablePipeline = args.Runspace;
 }
Ejemplo n.º 14
0
 private void HandleRunspaceCreated(object sender, RunspaceCreatedEventArgs args)
 {
     bool flag = false;
     if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce)
     {
         args.Runspace.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage;
         flag = true;
     }
     try
     {
         string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
         args.Runspace.ExecutionContext.EngineSessionState.SetLocation(folderPath);
     }
     catch (ArgumentException)
     {
     }
     catch (ProviderNotFoundException)
     {
     }
     catch (DriveNotFoundException)
     {
     }
     catch (ProviderInvocationException)
     {
     }
     if (this.configHash != null)
     {
         if (this.configHash.ContainsKey(ConfigFileContants.EnvironmentVariables))
         {
             Hashtable hashtable = this.configHash[ConfigFileContants.EnvironmentVariables] as Hashtable;
             if (hashtable != null)
             {
                 foreach (DictionaryEntry entry in hashtable)
                 {
                     string introduced76 = entry.Key.ToString();
                     this.InvokeScript(new Command(StringUtil.Format("$env:{0} = \"{1}\"", introduced76, entry.Value.ToString()), true, false), args);
                 }
             }
         }
         if (this.configHash.ContainsKey(ConfigFileContants.VariableDefinitions))
         {
             Hashtable[] hashtableArray = DISCPowerShellConfiguration.TryGetHashtableArray(this.configHash[ConfigFileContants.VariableDefinitions]);
             if (hashtableArray != null)
             {
                 foreach (Hashtable hashtable2 in hashtableArray)
                 {
                     if (hashtable2.ContainsKey(ConfigFileContants.VariableValueToken))
                     {
                         string str2 = DISCPowerShellConfiguration.TryGetValue(hashtable2, ConfigFileContants.VariableNameToken);
                         ScriptBlock block = hashtable2[ConfigFileContants.VariableValueToken] as ScriptBlock;
                         if (!string.IsNullOrEmpty(str2) && (block != null))
                         {
                             block.SessionStateInternal = args.Runspace.ExecutionContext.EngineSessionState;
                             PowerShell powershell = PowerShell.Create();
                             powershell.AddCommand(new Command("Invoke-Command")).AddParameter("ScriptBlock", block).AddParameter("NoNewScope");
                             powershell.AddCommand(new Command("Set-Variable")).AddParameter("Name", str2);
                             this.InvokePowerShell(powershell, args);
                         }
                     }
                 }
             }
         }
         if (this.configHash.ContainsKey(ConfigFileContants.ScriptsToProcess))
         {
             string[] strArray = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.ScriptsToProcess]);
             if (strArray != null)
             {
                 foreach (string str3 in strArray)
                 {
                     if (!string.IsNullOrEmpty(str3))
                     {
                         this.InvokeScript(new Command(str3, true, false), args);
                     }
                 }
             }
         }
         bool flag2 = false;
         if (this.configHash.ContainsKey(ConfigFileContants.VisibleAliases))
         {
             string[] strArray2 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleAliases]);
             if (strArray2 != null)
             {
                 flag2 = true;
                 foreach (KeyValuePair<string, AliasInfo> pair in args.Runspace.ExecutionContext.EngineSessionState.GetAliasTable())
                 {
                     bool flag3 = false;
                     foreach (string str4 in strArray2)
                     {
                         if (!string.IsNullOrEmpty(str4))
                         {
                             IEnumerable<WildcardPattern> patternList = this.CreateKeyPatternList(str4);
                             if (this.MatchKeyPattern(patternList, pair.Key))
                             {
                                 pair.Value.Visibility = SessionStateEntryVisibility.Public;
                                 flag3 = true;
                             }
                         }
                     }
                     if (!flag3)
                     {
                         pair.Value.Visibility = SessionStateEntryVisibility.Private;
                     }
                 }
             }
         }
         if (this.configHash.ContainsKey(ConfigFileContants.VisibleCmdlets))
         {
             string[] strArray3 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleCmdlets]);
             if (strArray3 != null)
             {
                 flag2 = true;
                 foreach (KeyValuePair<string, List<CmdletInfo>> pair2 in args.Runspace.ExecutionContext.EngineSessionState.GetCmdletTable())
                 {
                     bool flag4 = false;
                     foreach (string str5 in strArray3)
                     {
                         if (!string.IsNullOrEmpty(str5))
                         {
                             IEnumerable<WildcardPattern> enumerable2 = this.CreateKeyPatternList(str5);
                             if (this.MatchKeyPattern(enumerable2, pair2.Key))
                             {
                                 foreach (CmdletInfo info in pair2.Value)
                                 {
                                     info.Visibility = SessionStateEntryVisibility.Public;
                                     flag4 = true;
                                 }
                             }
                         }
                     }
                     if (!flag4)
                     {
                         foreach (CmdletInfo info2 in pair2.Value)
                         {
                             info2.Visibility = SessionStateEntryVisibility.Private;
                         }
                     }
                 }
             }
         }
         List<string> list = new List<string>();
         bool flag5 = false;
         if (this.configHash.ContainsKey(ConfigFileContants.VisibleFunctions))
         {
             string[] strArray4 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleFunctions]);
             if (strArray4 != null)
             {
                 flag2 = true;
                 flag5 = true;
                 list.AddRange(strArray4);
             }
         }
         if (!flag5 && this.configHash.ContainsKey(ConfigFileContants.FunctionDefinitions))
         {
             Hashtable[] hashtableArray2 = DISCPowerShellConfiguration.TryGetHashtableArray(this.configHash[ConfigFileContants.FunctionDefinitions]);
             if (hashtableArray2 != null)
             {
                 foreach (Hashtable hashtable3 in hashtableArray2)
                 {
                     string str6 = DISCPowerShellConfiguration.TryGetValue(hashtable3, ConfigFileContants.FunctionNameToken);
                     if (!string.IsNullOrEmpty(str6))
                     {
                         list.Add(str6);
                     }
                 }
             }
         }
         string str7 = DISCPowerShellConfiguration.TryGetValue(this.configHash, ConfigFileContants.SessionType);
         if (!string.IsNullOrEmpty(str7))
         {
             SessionType type = (SessionType) Enum.Parse(typeof(SessionType), str7, true);
             if (type == SessionType.RestrictedRemoteServer)
             {
                 list.Add("Get-Command");
                 list.Add("Get-FormatData");
                 list.Add("Select-Object");
                 list.Add("Get-Help");
                 list.Add("Measure-Object");
                 list.Add("Out-Default");
                 list.Add("Exit-PSSession");
             }
         }
         if (list.Count > 0)
         {
             foreach (DictionaryEntry entry2 in args.Runspace.ExecutionContext.EngineSessionState.GetFunctionTable())
             {
                 bool flag6 = false;
                 string key = entry2.Key.ToString();
                 FunctionInfo info3 = entry2.Value as FunctionInfo;
                 if (info3 != null)
                 {
                     foreach (string str9 in list)
                     {
                         if (!string.IsNullOrEmpty(str9))
                         {
                             IEnumerable<WildcardPattern> enumerable3 = this.CreateKeyPatternList(str9);
                             if (this.MatchKeyPattern(enumerable3, key))
                             {
                                 info3.Visibility = SessionStateEntryVisibility.Public;
                                 flag6 = true;
                             }
                         }
                     }
                     if (!flag6 && flag5)
                     {
                         info3.Visibility = SessionStateEntryVisibility.Private;
                     }
                 }
             }
         }
         if (this.configHash.ContainsKey(ConfigFileContants.VisibleProviders))
         {
             string[] strArray5 = DISCPowerShellConfiguration.TryGetStringArray(this.configHash[ConfigFileContants.VisibleProviders]);
             if (strArray5 != null)
             {
                 flag2 = true;
                 IDictionary<string, List<ProviderInfo>> providers = args.Runspace.ExecutionContext.EngineSessionState.Providers;
                 Collection<string> collection = new Collection<string>();
                 foreach (KeyValuePair<string, List<ProviderInfo>> pair3 in providers)
                 {
                     bool flag7 = false;
                     foreach (string str10 in strArray5)
                     {
                         if (!string.IsNullOrEmpty(str10))
                         {
                             IEnumerable<WildcardPattern> enumerable4 = this.CreateKeyPatternList(str10);
                             if (this.MatchKeyPattern(enumerable4, pair3.Key))
                             {
                                 flag7 = true;
                             }
                         }
                     }
                     if (!flag7)
                     {
                         collection.Add(pair3.Key);
                     }
                 }
                 foreach (string str11 in collection)
                 {
                     args.Runspace.ExecutionContext.EngineSessionState.Providers.Remove(str11);
                 }
             }
         }
         if (flag2)
         {
             CmdletInfo cmdlet = args.Runspace.ExecutionContext.SessionState.InvokeCommand.GetCmdlet(@"Microsoft.PowerShell.Core\Import-Module");
             IDictionary<string, AliasInfo> aliasTable = args.Runspace.ExecutionContext.EngineSessionState.GetAliasTable();
             PSModuleAutoLoadingPreference preference = CommandDiscovery.GetCommandDiscoveryPreference(args.Runspace.ExecutionContext, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference");
             bool flag8 = (cmdlet != null) && (cmdlet.Visibility != SessionStateEntryVisibility.Private);
             bool flag9 = ((aliasTable != null) && aliasTable.ContainsKey("ipmo")) && (aliasTable["ipmo"].Visibility != SessionStateEntryVisibility.Private);
             if ((flag8 || flag9) && (preference == PSModuleAutoLoadingPreference.None))
             {
                 throw new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.DISCVisibilityAndAutoLoadingCannotBeBothSpecified, new object[] { "Import-Module", "ipmo", ConfigFileContants.VisibleCmdlets, ConfigFileContants.VisibleAliases, ConfigFileContants.VisibleFunctions, ConfigFileContants.VisibleProviders }));
             }
         }
         if (this.configHash.ContainsKey(ConfigFileContants.LanguageMode))
         {
             PSLanguageMode mode = (PSLanguageMode) Enum.Parse(typeof(PSLanguageMode), this.configHash[ConfigFileContants.LanguageMode].ToString(), true);
             if (flag && (mode != PSLanguageMode.ConstrainedLanguage))
             {
                 throw new PSInvalidOperationException(RemotingErrorIdStrings.CannotCreateRunspaceInconsistentState);
             }
             args.Runspace.ExecutionContext.LanguageMode = mode;
         }
         if (this.configHash.ContainsKey(ConfigFileContants.ExecutionPolicy))
         {
             ExecutionPolicy policy = (ExecutionPolicy) Enum.Parse(typeof(ExecutionPolicy), this.configHash[ConfigFileContants.ExecutionPolicy].ToString(), true);
             string shellID = args.Runspace.ExecutionContext.ShellID;
             SecuritySupport.SetExecutionPolicy(ExecutionPolicyScope.Process, policy, shellID);
         }
     }
     Command cmdToRun = null;
     if (!string.IsNullOrEmpty(this.configData.StartupScript))
     {
         cmdToRun = new Command(this.configData.StartupScript, false, false);
     }
     else if (!string.IsNullOrEmpty(this.configData.InitializationScriptForOutOfProcessRunspace))
     {
         cmdToRun = new Command(this.configData.InitializationScriptForOutOfProcessRunspace, true, false);
     }
     if (cmdToRun != null)
     {
         this.InvokeScript(cmdToRun, args);
         if (this.localRunspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opening)
         {
             object valueToConvert = args.Runspace.SessionStateProxy.PSVariable.GetValue("global:PSApplicationPrivateData");
             if (valueToConvert != null)
             {
                 this.applicationPrivateData = (PSPrimitiveDictionary) LanguagePrimitives.ConvertTo(valueToConvert, typeof(PSPrimitiveDictionary), true, CultureInfo.InvariantCulture, null);
             }
         }
     }
 }