internal Collection <string> GetSearchPaths() { if (this._searchPaths == null) { this._searchPaths = new Collection <string>(); RunspaceConfigForSingleShell runspaceConfiguration = this.ExecutionContext.RunspaceConfiguration as RunspaceConfigForSingleShell; if (runspaceConfiguration != null) { MshConsoleInfo consoleInfo = runspaceConfiguration.ConsoleInfo; if ((consoleInfo == null) || (consoleInfo.ExternalPSSnapIns == null)) { return(this._searchPaths); } foreach (PSSnapInInfo info2 in consoleInfo.ExternalPSSnapIns) { this._searchPaths.Add(info2.ApplicationBase); } } if (this.ExecutionContext.Modules != null) { foreach (PSModuleInfo info3 in this.ExecutionContext.Modules.ModuleTable.Values) { this._searchPaths.Add(info3.ModuleBase); } } } return(this._searchPaths); }
private CommandProcessorBase CreateScriptProcessorForSingleShell( ExternalScriptInfo scriptInfo, RunspaceConfigForSingleShell ssRunConfig, bool useLocalScope) { CommandDiscovery.VerifyPSVersion(scriptInfo); Collection <PSSnapInNameVersionPair> requiresPsSnapIns = scriptInfo.RequiresPSSnapIns; if (requiresPsSnapIns != null) { Collection <string> missingPSSnapIns = (Collection <string>)null; foreach (PSSnapInNameVersionPair PSSnapin in requiresPsSnapIns) { Collection <PSSnapInInfo> psSnapIn = ssRunConfig.ConsoleInfo.GetPSSnapIn(PSSnapin.PSSnapInName, false); if (psSnapIn == null || psSnapIn.Count == 0) { if (missingPSSnapIns == null) { missingPSSnapIns = new Collection <string>(); } missingPSSnapIns.Add(CommandDiscovery.BuildPSSnapInDisplayName(PSSnapin)); } else if (PSSnapin.Version != (Version)null && !CommandDiscovery.AreInstalledRequiresVersionsCompatible(PSSnapin.Version, psSnapIn[0].Version)) { if (missingPSSnapIns == null) { missingPSSnapIns = new Collection <string>(); } missingPSSnapIns.Add(CommandDiscovery.BuildPSSnapInDisplayName(PSSnapin)); } } if (missingPSSnapIns != null) { ScriptRequiresException requiresException = new ScriptRequiresException(scriptInfo.Name, missingPSSnapIns, "ScriptRequiresMissingPSSnapIns"); CommandDiscovery.tracer.TraceException((Exception)requiresException); throw requiresException; } } else if (!string.IsNullOrEmpty(scriptInfo.RequiresApplicationID)) { CommandDiscovery.GetShellPathFromRegistry(scriptInfo.RequiresApplicationID); ScriptRequiresException requiresException = new ScriptRequiresException(scriptInfo.Name, scriptInfo.ApplicationIDLineNumber, string.Empty, string.Empty, "RequiresShellIDInvalidForSingleShell"); CommandDiscovery.tracer.TraceException((Exception)requiresException); throw requiresException; } return(CommandDiscovery.CreateCommandProcessorForScript(scriptInfo, this._context, useLocalScope)); }
/// <summary> /// Set the $Console variable in this session state instance... /// </summary> internal void SetConsoleVariable() { // $Console - set the console file for this shell, if there is one, "" otherwise... string consoleFileName = string.Empty; RunspaceConfigForSingleShell rcss = ExecutionContext.RunspaceConfiguration as RunspaceConfigForSingleShell; if (rcss != null && rcss.ConsoleInfo != null && !string.IsNullOrEmpty(rcss.ConsoleInfo.Filename)) { consoleFileName = rcss.ConsoleInfo.Filename; } PSVariable v = new PSVariable(SpecialVariables.ConsoleFileName, consoleFileName, ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope, RunspaceInit.ConsoleDescription); this.GlobalScope.SetVariable(v.Name, v, false, true, this, CommandOrigin.Internal, fastPath: true); }
/// <summary> /// Gets the search paths for external snapins/modules that are currently loaded. /// If the current shell is single-shell based, then the returned /// search path contains all the directories of currently active PSSnapIns/modules. /// </summary> /// <returns>a collection of strings representing locations</returns> internal Collection <string> GetSearchPaths() { // return the cache if already present. if (null != _searchPaths) { return(_searchPaths); } _searchPaths = new Collection <String>(); RunspaceConfigForSingleShell runspace = this.ExecutionContext.RunspaceConfiguration as RunspaceConfigForSingleShell; if (null != runspace) { // SingleShell case. Check active snapins... MshConsoleInfo currentConsole = runspace.ConsoleInfo; if ((null == currentConsole) || (null == currentConsole.ExternalPSSnapIns)) { return(_searchPaths); } foreach (PSSnapInInfo snapin in currentConsole.ExternalPSSnapIns) { _searchPaths.Add(snapin.ApplicationBase); } } // add loaded modules paths to the search path if (null != ExecutionContext.Modules) { foreach (PSModuleInfo loadedModule in ExecutionContext.Modules.ModuleTable.Values) { if (!_searchPaths.Contains(loadedModule.ModuleBase)) { _searchPaths.Add(loadedModule.ModuleBase); } } } return(_searchPaths); }
/// <summary> /// Helper function which checks whether PSSnapIns are supported in current invocation. /// </summary> /// <returns>true if supported,false otherwise.</returns> internal bool AreSnapInsSupported() { RunspaceConfigForSingleShell runspace = _helpSystem.ExecutionContext.RunspaceConfiguration as RunspaceConfigForSingleShell; return(null == runspace ? false : true); }
#pragma warning restore 1573 #else public int Start(string consoleFilePath, string[] args) #endif { #if !CORECLR // For long-path support, Full .NET requires some AppContext switches; // (for CoreCLR this is Not needed, because CoreCLR supports long paths by default) // internally in .NET they are cached once retrieved and are typically hit very early during an application run; // so per .NET team's recommendation, we are setting them as soon as we enter managed code. EnableLongPathsInDotNetIfAvailable(); #endif System.Management.Automation.Runspaces.EarlyStartup.Init(); // Set ETW activity Id Guid activityId = EtwActivity.GetActivityId(); if (activityId == Guid.Empty) { EtwActivity.SetActivityId(EtwActivity.CreateActivityId()); } PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStart, PSOpcode.WinStart, PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational); #if !CORECLR // Register crash reports in non-server mode WindowsErrorReporting.RegisterWindowsErrorReporting(false); #endif try { // Windows Vista and later support non-traditional UI fallback ie., a // user on an Arabic machine can choose either French or English(US) as // UI fallback language. // CLR does not support this (non-traditional) fallback mechanism. // The currentUICulture returned NativeCultureResolver supports this non // traditional fallback on Vista. So it is important to set currentUICulture // in the beginning before we do anything. ClrFacade.SetCurrentThreadUiCulture(NativeCultureResolver.UICulture); ClrFacade.SetCurrentThreadCulture(NativeCultureResolver.Culture); RunspaceConfigForSingleShell configuration = null; PSConsoleLoadException warning = null; // PSSnapInException will cause the control to return back to the native code // and stuff the EXCEPINFO field with the message of the exception. // The native code will print this out and exit the process. if (string.IsNullOrEmpty(consoleFilePath)) { #if DEBUG // Special switches for debug mode to allow self-hosting on InitialSessionState instead // of runspace configuration... if (args.Length > 0 && !String.IsNullOrEmpty(args[0]) && args[0].Equals("-iss", StringComparison.OrdinalIgnoreCase)) { ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); configuration = null; } else if (args.Length > 0 && !String.IsNullOrEmpty(args[0]) && args[0].Equals("-isswait", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("Attach the debugger and hit enter to continue:"); Console.ReadLine(); ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); configuration = null; } else { ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); configuration = null; } #else ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); configuration = null; #endif } else { //TODO : Deprecate RunspaceConfiguration and use InitialSessionState configuration = RunspaceConfigForSingleShell.Create(consoleFilePath, out warning); } int exitCode = 0; try { #if CORECLR var banner = ManagedEntranceStrings.ShellBannerNonWindowsPowerShell; #else var banner = ManagedEntranceStrings.ShellBanner; #endif exitCode = Microsoft.PowerShell.ConsoleShell.Start( configuration, banner, ManagedEntranceStrings.ShellHelp, warning == null ? null : warning.Message, args); } catch (System.Management.Automation.Host.HostException e) { if (e.InnerException != null && e.InnerException.GetType() == typeof(System.ComponentModel.Win32Exception)) { System.ComponentModel.Win32Exception win32e = e.InnerException as System.ComponentModel.Win32Exception; // These exceptions are caused by killing conhost.exe // 1236, network connection aborted by local system // 0x6, invalid console handle if (win32e.NativeErrorCode == 0x6 || win32e.NativeErrorCode == 1236) { return(exitCode); } } #if CORECLR System.Environment.FailFast(e.Message); #else WindowsErrorReporting.FailFast(e); #endif } catch (Exception e) { #if CORECLR System.Management.Automation.Environment.FailFast(e.Message); #else // exceptions caught here should cause Watson. // Must call FailFast; otherwise the exception will be returned to the native code // which will just print out the exception message without Watson WindowsErrorReporting.FailFast(e); #endif } return(exitCode); } finally { #if !CORECLR WindowsErrorReporting.WaitForPendingReports(); #endif } }
internal CommandProcessorBase LookupCommandProcessor( CommandInfo commandInfo, CommandOrigin commandOrigin, bool?useLocalScope) { if (commandInfo.CommandType == CommandTypes.Alias && (commandOrigin == CommandOrigin.Internal || commandInfo.Visibility == SessionStateEntryVisibility.Public)) { AliasInfo aliasInfo = (AliasInfo)commandInfo; commandInfo = aliasInfo.ResolvedCommand; if (commandInfo == null) { CommandNotFoundException notFoundException = new CommandNotFoundException(aliasInfo.Name, (Exception)null, "AliasNotResolvedException", new object[1] { (object)aliasInfo.UnresolvedCommandName }); CommandDiscovery.tracer.TraceException((Exception)notFoundException); throw notFoundException; } PSSQMAPI.IncrementData(CommandTypes.Alias); } CommandDiscovery.ShouldRun(this._context, (PSHost)this._context.EngineHostInterface, commandInfo, commandOrigin); CommandProcessorBase commandProcessorBase; switch (commandInfo.CommandType) { case CommandTypes.Function: case CommandTypes.Filter: FunctionInfo functionInfo = (FunctionInfo)commandInfo; ExecutionContext context1 = this._context; bool? nullable1 = useLocalScope; int num1 = nullable1.HasValue ? (nullable1.GetValueOrDefault() ? 1 : 0) : 1; commandProcessorBase = CommandDiscovery.CreateCommandProcessorForScript(functionInfo, context1, num1 != 0); break; case CommandTypes.Cmdlet: commandProcessorBase = (CommandProcessorBase) new CommandProcessor((CmdletInfo)commandInfo, this._context); break; case CommandTypes.ExternalScript: ExternalScriptInfo externalScriptInfo = (ExternalScriptInfo)commandInfo; externalScriptInfo.SignatureChecked = true; try { if (!this._context.IsSingleShell) { ExternalScriptInfo scriptInfo = externalScriptInfo; bool?nullable2 = useLocalScope; int num2 = nullable2.HasValue ? (nullable2.GetValueOrDefault() ? 1 : 0) : 1; commandProcessorBase = this.CreateScriptProcessorForMiniShell(scriptInfo, num2 != 0); break; } ExternalScriptInfo scriptInfo1 = externalScriptInfo; RunspaceConfigForSingleShell runspaceConfiguration = this._context.RunspaceConfiguration as RunspaceConfigForSingleShell; bool?nullable3 = useLocalScope; int num3 = nullable3.HasValue ? (nullable3.GetValueOrDefault() ? 1 : 0) : 1; commandProcessorBase = this.CreateScriptProcessorForSingleShell(scriptInfo1, runspaceConfiguration, num3 != 0); break; } catch (ScriptRequiresSyntaxException ex) { CommandNotFoundException notFoundException = new CommandNotFoundException(ex.Message, (Exception)ex); CommandDiscovery.tracer.TraceException((Exception)notFoundException); throw notFoundException; } catch (PSArgumentException ex) { CommandNotFoundException notFoundException = new CommandNotFoundException(commandInfo.Name, (Exception)ex, "ScriptRequiresInvalidFormat", new object[0]); CommandDiscovery.tracer.TraceException((Exception)notFoundException); throw notFoundException; } case CommandTypes.Application: commandProcessorBase = (CommandProcessorBase) new NativeCommandProcessor((ApplicationInfo)commandInfo, this._context); break; case CommandTypes.Script: ScriptInfo scriptInfo2 = (ScriptInfo)commandInfo; ExecutionContext context2 = this._context; bool? nullable4 = useLocalScope; int num4 = nullable4.HasValue ? (nullable4.GetValueOrDefault() ? 1 : 0) : 1; commandProcessorBase = CommandDiscovery.CreateCommandProcessorForScript(scriptInfo2, context2, num4 != 0); break; default: CommandNotFoundException notFoundException1 = new CommandNotFoundException(commandInfo.Name, (Exception)null, "CommandNotFoundException", new object[0]); CommandDiscovery.tracer.TraceException((Exception)notFoundException1); throw notFoundException1; } PSSQMAPI.IncrementData(commandInfo.CommandType); commandProcessorBase.Command.CommandOriginInternal = commandOrigin; commandProcessorBase.Command.MyInvocation.InvocationName = commandInfo.Name; return(commandProcessorBase); }
public int Start(string consoleFilePath, string[] args) { int num; string message; Guid activityId = EtwActivity.GetActivityId(); if (activityId == Guid.Empty) { EtwActivity.SetActivityId(EtwActivity.CreateActivityId()); } PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStart, PSOpcode.WinStart, PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational, new object[0]); WindowsErrorReporting.RegisterWindowsErrorReporting(false); try { Thread.CurrentThread.CurrentUICulture = NativeCultureResolver.UICulture; Thread.CurrentThread.CurrentCulture = NativeCultureResolver.Culture; RunspaceConfigForSingleShell runspaceConfigForSingleShell = null; PSConsoleLoadException pSConsoleLoadException = null; if (!string.IsNullOrEmpty(consoleFilePath)) { runspaceConfigForSingleShell = RunspaceConfigForSingleShell.Create(consoleFilePath, out pSConsoleLoadException); } else { ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); runspaceConfigForSingleShell = null; if (Process.GetCurrentProcess().MainWindowHandle != IntPtr.Zero) { ConsoleHost.DefaultInitialSessionState.WarmUpTabCompletionOnIdle = true; } } int num1 = 0; try { RunspaceConfigForSingleShell runspaceConfigForSingleShell1 = runspaceConfigForSingleShell; string shellBanner = ManagedEntranceStrings.ShellBanner; string shellHelp = ManagedEntranceStrings.ShellHelp; if (pSConsoleLoadException == null) { message = null; } else { message = pSConsoleLoadException.Message; } num1 = ConsoleShell.Start(runspaceConfigForSingleShell1, shellBanner, shellHelp, message, args); } catch (HostException hostException1) { HostException hostException = hostException1; if (hostException.InnerException != null && hostException.InnerException.GetType() == typeof(Win32Exception)) { Win32Exception innerException = hostException.InnerException as Win32Exception; if (innerException.NativeErrorCode == 6 || innerException.NativeErrorCode == 0x4d4) { num = num1; return(num); } } WindowsErrorReporting.FailFast(hostException); } catch (Exception exception1) { Exception exception = exception1; WindowsErrorReporting.FailFast(exception); } num = num1; } finally { WindowsErrorReporting.WaitForPendingReports(); } return(num); }
/// <summary> /// Starts managed MSH /// </summary> /// <param name="consoleFilePath"> /// Console file used to create a runspace configuration to start MSH /// </param> /// <param name="args"> /// Command line arguments to the managed MSH /// </param> #pragma warning disable 1573 public static int Start(string consoleFilePath, [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 2)] string[] args, int argc) #pragma warning restore 1573 { System.Management.Automation.Runspaces.EarlyStartup.Init(); // Set ETW activity Id Guid activityId = EtwActivity.GetActivityId(); if (activityId == Guid.Empty) { EtwActivity.SetActivityId(EtwActivity.CreateActivityId()); } PSEtwLog.LogOperationalInformation(PSEventId.Perftrack_ConsoleStartupStart, PSOpcode.WinStart, PSTask.PowershellConsoleStartup, PSKeyword.UseAlwaysOperational); // Windows Vista and later support non-traditional UI fallback ie., a // user on an Arabic machine can choose either French or English(US) as // UI fallback language. // CLR does not support this (non-traditional) fallback mechanism. // The currentUICulture returned NativeCultureResolver supports this non // traditional fallback on Vista. So it is important to set currentUICulture // in the beginning before we do anything. Thread.CurrentThread.CurrentUICulture = NativeCultureResolver.UICulture; Thread.CurrentThread.CurrentCulture = NativeCultureResolver.Culture; RunspaceConfigForSingleShell configuration = null; PSConsoleLoadException warning = null; // PSSnapInException will cause the control to return back to the native code // and stuff the EXCEPINFO field with the message of the exception. // The native code will print this out and exit the process. if (string.IsNullOrEmpty(consoleFilePath)) { #if DEBUG // Special switches for debug mode to allow self-hosting on InitialSessionState instead // of runspace configuration... if (args.Length > 0 && !String.IsNullOrEmpty(args[0]) && args[0].Equals("-iss", StringComparison.OrdinalIgnoreCase)) { ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); configuration = null; } else if (args.Length > 0 && !String.IsNullOrEmpty(args[0]) && args[0].Equals("-isswait", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("Attach the debugger and hit enter to continue:"); Console.ReadLine(); ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); configuration = null; } else { ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); configuration = null; } #else ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); configuration = null; #endif } else { //TODO : Deprecate RunspaceConfiguration and use InitialSessionState configuration = RunspaceConfigForSingleShell.Create(consoleFilePath, out warning); } int exitCode = 0; try { var banner = ManagedEntranceStrings.ShellBannerNonWindowsPowerShell; var formattedBanner = string.Format(CultureInfo.InvariantCulture, banner, PSVersionInfo.GitCommitId); exitCode = Microsoft.PowerShell.ConsoleShell.Start( configuration, formattedBanner, ManagedEntranceStrings.ShellHelp, warning == null ? null : warning.Message, args); } catch (System.Management.Automation.Host.HostException e) { if (e.InnerException != null && e.InnerException.GetType() == typeof(System.ComponentModel.Win32Exception)) { System.ComponentModel.Win32Exception win32e = e.InnerException as System.ComponentModel.Win32Exception; // These exceptions are caused by killing conhost.exe // 1236, network connection aborted by local system // 0x6, invalid console handle if (win32e.NativeErrorCode == 0x6 || win32e.NativeErrorCode == 1236) { return(exitCode); } } System.Environment.FailFast(e.Message, e); } catch (Exception e) { System.Environment.FailFast(e.Message, e); } return(exitCode); }