/// <summary> /// Dispose off the current runspace pool /// </summary> /// <param name="disposing"> /// true to release all the internal resources. /// </param> public virtual void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { Close(); _cleanupTimer.Dispose(); _initialSessionState = null; host = null; } _isDisposed = true; } }
static void Main() { //Box(new List<string> {"abc", " def", "this is something coo"}); var iss = InitialSessionState.CreateDefault2(); var rs = RunspaceFactory.CreateRunspace(iss); rs.Open(); Runspace.DefaultRunspace = rs; PSConsoleReadLine.SetOptions(new SetPSReadlineOption { EditMode = EditMode.Emacs, HistoryNoDuplicates = true, }); PSConsoleReadLine.SetKeyHandler(new[] { "Ctrl+LeftArrow" }, PSConsoleReadLine.ShellBackwardWord, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "Ctrl+RightArrow" }, PSConsoleReadLine.ShellNextWord, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "F4" }, PSConsoleReadLine.HistorySearchBackward, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "F5" }, PSConsoleReadLine.HistorySearchForward, "", ""); //PSConsoleReadLine.SetKeyHandler(new[] {"Ctrl+D,Ctrl+E"}, PSConsoleReadLine.EnableDemoMode, "", ""); //PSConsoleReadLine.SetKeyHandler(new[] {"Ctrl+D,Ctrl+D"}, PSConsoleReadLine.DisableDemoMode, "", ""); // PSConsoleReadLine.SetKeyHandler(new[] {"Ctrl+D,Ctrl+C"}, PSConsoleReadLine.CaptureScreen, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "Ctrl+D,Ctrl+P" }, PSConsoleReadLine.InvokePrompt, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "Ctrl+D,Ctrl+X" }, CauseCrash, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "F6" }, PSConsoleReadLine.PreviousLine, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "F7" }, PSConsoleReadLine.NextLine, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "F2" }, PSConsoleReadLine.ValidateAndAcceptLine, "", ""); PSConsoleReadLine.SetKeyHandler(new[] { "Enter" }, PSConsoleReadLine.AcceptLine, "", ""); EngineIntrinsics executionContext; using (var ps = PowerShell.Create(RunspaceMode.CurrentRunspace)) { executionContext = ps.AddScript("$ExecutionContext").Invoke <EngineIntrinsics>().FirstOrDefault(); // This is a workaround to ensure the command analysis cache has been created before // we enter into ReadLine. It's a little slow and infrequently needed, so just // uncomment host stops responding, run it once, then comment it out again. //ps.Commands.Clear(); //ps.AddCommand("Get-Command").Invoke(); } while (true) { Console.Write("TestHostPS> "); var line = PSConsoleReadLine.ReadLine(null, executionContext); Console.WriteLine(line); line = line.Trim(); if (line.Equals("exit")) { Environment.Exit(0); } if (line.Equals("cmd")) { PSConsoleReadLine.SetOptions(new SetPSReadlineOption { EditMode = EditMode.Windows }); } if (line.Equals("emacs")) { PSConsoleReadLine.SetOptions(new SetPSReadlineOption { EditMode = EditMode.Emacs }); } if (line.Equals("vi")) { PSConsoleReadLine.SetOptions(new SetPSReadlineOption { EditMode = EditMode.Vi }); } if (line.Equals("nodupes")) { PSConsoleReadLine.SetOptions(new SetPSReadlineOption { HistoryNoDuplicates = true }); } } }
/// <summary> /// Constructor which creates a RunspacePool using the /// supplied <paramref name="configuration"/>, <paramref name="minRunspaces"/> /// and <paramref name="maxRunspaces"/> /// </summary> /// <param name="initialSessionState"> /// InitialSessionState to use when creating a new Runspace. /// </param> /// <param name="maxRunspaces"> /// The maximum number of Runspaces that can exist in this pool. /// Should be greater than or equal to 1. /// </param> /// <param name="minRunspaces"> /// The minimum number of Runspaces that can exist in this pool. /// Should be greater than or equal to 1. /// </param> /// <param name="host"> /// The explicit PSHost implementation. /// </param> /// <exception cref="ArgumentNullException"> /// initialSessionState is null. /// Host is null. /// </exception> /// <exception cref="ArgumentException"> /// Maximum runspaces is less than 1. /// Minimum runspaces is less than 1. /// </exception> public RunspacePoolInternal(int minRunspaces, int maxRunspaces, InitialSessionState initialSessionState, PSHost host) : this(minRunspaces, maxRunspaces) { if (initialSessionState == null) { throw PSTraceSource.NewArgumentNullException("initialSessionState"); } if (host == null) { throw PSTraceSource.NewArgumentNullException("host"); } _initialSessionState = initialSessionState.Clone(); this.host = host; ThreadOptions = initialSessionState.ThreadOptions; #if !CORECLR // No ApartmentState In CoreCLR this.ApartmentState = initialSessionState.ApartmentState; #endif pool = new Stack<Runspace>(); runspaceRequestQueue = new Queue<GetRunspaceAsyncResult>(); ultimateRequestQueue = new Queue<GetRunspaceAsyncResult>(); }
public PowerShellExecutionResults run_host(ChocolateyConfiguration config, string chocoPowerShellScript, Action <Pipeline> additionalActionsBeforeScript) { // since we control output in the host, always set these true Environment.SetEnvironmentVariable("ChocolateyEnvironmentDebug", "true"); Environment.SetEnvironmentVariable("ChocolateyEnvironmentVerbose", "true"); var result = new PowerShellExecutionResults(); string commandToRun = wrap_script_with_module(chocoPowerShellScript, config); var host = new PoshHost(config); this.Log().Debug(() => "Calling built-in PowerShell host with ['{0}']".format_with(commandToRun.escape_curly_braces())); var initialSessionState = InitialSessionState.CreateDefault(); // override system execution policy without accidentally setting it initialSessionState.AuthorizationManager = new AuthorizationManager("choco"); using (var runspace = RunspaceFactory.CreateRunspace(host, initialSessionState)) { runspace.Open(); // this will affect actual execution policy //RunspaceInvoke invoker = new RunspaceInvoke(runspace); //invoker.Invoke("Set-ExecutionPolicy ByPass"); using (var pipeline = runspace.CreatePipeline()) { // The powershell host itself handles the following items: // * Write-Debug // * Write-Host // * Write-Verbose // * Write-Warning // // the two methods below will pick up Write-Output and Write-Error // Write-Output pipeline.Output.DataReady += (sender, args) => { PipelineReader <PSObject> reader = sender as PipelineReader <PSObject>; if (reader != null) { while (reader.Count > 0) { host.UI.WriteLine(reader.Read().to_string().escape_curly_braces()); } } }; // Write-Error pipeline.Error.DataReady += (sender, args) => { PipelineReader <object> reader = sender as PipelineReader <object>; if (reader != null) { while (reader.Count > 0) { host.UI.WriteErrorLine(reader.Read().to_string().escape_curly_braces()); } } }; var documentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.DoNotVerify); var currentUserCurrentHostProfile = _fileSystem.combine_paths(documentsFolder, "WindowsPowerShell\\Microsoft.PowerShell_profile.ps1"); var recreateProfileScript = @" if ((Test-Path(""{0}"")) -and ($profile -eq $null -or $profile -eq '')) {{ $global:profile = ""{1}"" }} ".format_with(documentsFolder, currentUserCurrentHostProfile); pipeline.Commands.Add(new Command(recreateProfileScript, isScript: true, useLocalScope: false)); // The PowerShell Output Redirection bug affects System.Management.Automation // it appears with v3 more than others. It is already known to affect v2 // this implements the redirection fix from the post below, fixed up with some comments // http://www.leeholmes.com/blog/2008/07/30/workaround-the-os-handles-position-is-not-what-filestream-expected/ const string outputRedirectionFixScript = @" try { $bindingFlags = [Reflection.BindingFlags] ""Instance,NonPublic,GetField"" $objectRef = $host.GetType().GetField(""externalHostRef"", $bindingFlags).GetValue($host) $bindingFlags = [Reflection.BindingFlags] ""Instance,NonPublic,GetProperty"" $consoleHost = $objectRef.GetType().GetProperty(""Value"", $bindingFlags).GetValue($objectRef, @()) [void] $consoleHost.GetType().GetProperty(""IsStandardOutputRedirected"", $bindingFlags).GetValue($consoleHost, @()) $bindingFlags = [Reflection.BindingFlags] ""Instance,NonPublic,GetField"" $field = $consoleHost.GetType().GetField(""standardOutputWriter"", $bindingFlags) $field.SetValue($consoleHost, [Console]::Out) [void] $consoleHost.GetType().GetProperty(""IsStandardErrorRedirected"", $bindingFlags).GetValue($consoleHost, @()) $field2 = $consoleHost.GetType().GetField(""standardErrorWriter"", $bindingFlags) $field2.SetValue($consoleHost, [Console]::Error) } catch { Write-Output ""Unable to apply redirection fix"" } "; pipeline.Commands.Add(new Command(outputRedirectionFixScript, isScript: true, useLocalScope: false)); if (additionalActionsBeforeScript != null) { additionalActionsBeforeScript.Invoke(pipeline); } pipeline.Commands.Add(new Command(commandToRun, isScript: true, useLocalScope: false)); try { pipeline.Invoke(); } catch (RuntimeException ex) { var errorStackTrace = ex.StackTrace; var record = ex.ErrorRecord; if (record != null) { // not available in v1 //errorStackTrace = record.ScriptStackTrace; var scriptStackTrace = record.GetType().GetProperty("ScriptStackTrace"); if (scriptStackTrace != null) { var scriptError = scriptStackTrace.GetValue(record, null).to_string(); if (!string.IsNullOrWhiteSpace(scriptError)) { errorStackTrace = scriptError; } } } this.Log().Error("ERROR: {0}{1}".format_with(ex.Message.escape_curly_braces(), !config.Debug ? string.Empty : "{0} {1}".format_with(Environment.NewLine, errorStackTrace.escape_curly_braces()))); } catch (Exception ex) { // Unfortunately this doesn't print line number and character. It might be nice to get back to those items unless it involves tons of work. this.Log().Error("ERROR: {0}{1}".format_with(ex.Message.escape_curly_braces(), !config.Debug ? string.Empty : "{0} {1}".format_with(Environment.NewLine, ex.StackTrace.escape_curly_braces()))); } if (pipeline.PipelineStateInfo != null) { switch (pipeline.PipelineStateInfo.State) { // disconnected is not available unless the assembly version is at least v3 //case PipelineState.Disconnected: case PipelineState.Running: case PipelineState.NotStarted: case PipelineState.Failed: case PipelineState.Stopping: case PipelineState.Stopped: if (host.ExitCode == 0) { host.SetShouldExit(1); } host.HostException = pipeline.PipelineStateInfo.Reason; break; case PipelineState.Completed: if (host.ExitCode == -1) { host.SetShouldExit(0); } break; } } } } this.Log().Debug("Built-in PowerShell host called with ['{0}'] exited with '{1}'.".format_with(commandToRun.escape_curly_braces(), host.ExitCode)); result.ExitCode = host.ExitCode; result.StandardErrorWritten = host.StandardErrorWritten; return(result); }
/// <summary> /// By default serialization preserves all public properties of an object. /// /// This sample looks at an existing .NET class and shows how to make sure that /// information from instance of this class is preserved across serialization/deserialization /// when the information is not available in public properties of the class /// </summary> static void Main() { string typesPs1XmlPath = Path.Combine(Environment.CurrentDirectory, "Serialization02.types.ps1xml"); if (!File.Exists(typesPs1XmlPath)) { Console.WriteLine("Building the project in Visual Studio should have created a types.ps1xml file at the following path:"); Console.WriteLine("{0}", typesPs1XmlPath); Console.WriteLine(); Console.WriteLine("Cannot continue without this file being present."); return; } // Create a default InitialSessionState InitialSessionState iss = InitialSessionState.CreateDefault(); // Add our types.ps1xml file to the InitialSessionState // (one alternative would be to associate the file with a module or with a snap-in) iss.Types.Add(new SessionStateTypeEntry(typesPs1XmlPath)); // // Demonstrate the effects of the types.ps1xml and DeserializingTypeConverter // using (Runspace myRunspace = RunspaceFactory.CreateRunspace(iss)) { myRunspace.Open(); // // Demonstrate that the deserializing an exception results in a live object // using (PowerShell powershell = PowerShell.Create()) { powershell.Runspace = myRunspace; powershell.AddScript(@" # Get an System.Drawing.Point object Add-Type -AssemblyName System.Drawing $point = New-Object System.Drawing.Point 12,34 # Verify that the extra property is hidden by default Write-Output 'Below are the results of running $point | Format-List * :' $point | Format-List * | Out-String Write-Output '----------------------------------------' # Serialize the object $point | Export-CliXml .\Serialization02.xml # Deserialize the object $deserializedPoint = Import-CliXml .\Serialization02.xml # Verify that the extra property got serialized Write-Output 'Below are the results of running $deserializedPoint | Get-Member :' $deserializedPoint | Get-Member | Out-String Write-Output '----------------------------------------' "); foreach (string s in powershell.Invoke <string>()) { System.Console.WriteLine(s); } } // Close the runspace and release any resources. myRunspace.Close(); } System.Console.WriteLine("Hit any key to exit..."); System.Console.ReadKey(); }
/// <summary> /// The principal constructor that most hosts will use when creating /// an instance of the automation engine. It allows you to pass in an /// instance of PSHost that provides the host-specific I/O routines, etc. /// </summary> internal AutomationEngine(PSHost hostInterface, RunspaceConfiguration runspaceConfiguration, InitialSessionState iss) { #if !CORECLR// There is no control panel items in CSS // Update the env variable PathEXT to contain .CPL var pathext = Environment.GetEnvironmentVariable("PathEXT"); pathext = pathext ?? string.Empty; bool cplExist = false; if (pathext != string.Empty) { string[] entries = pathext.Split(Utils.Separators.Semicolon); foreach (string entry in entries) { string ext = entry.Trim(); if (ext.Equals(".CPL", StringComparison.OrdinalIgnoreCase)) { cplExist = true; break; } } } if (!cplExist) { pathext = (pathext == string.Empty) ? ".CPL" : pathext.EndsWith(";", StringComparison.OrdinalIgnoreCase) ? (pathext + ".CPL") : (pathext + ";.CPL"); Environment.SetEnvironmentVariable("PathEXT", pathext); } #endif if (runspaceConfiguration != null) { Context = new ExecutionContext(this, hostInterface, runspaceConfiguration); } else { Context = new ExecutionContext(this, hostInterface, iss); } EngineParser = new Language.Parser(); CommandDiscovery = new CommandDiscovery(Context); // Initialize providers before loading types so that any ScriptBlocks in the // types.ps1xml file can be parsed. // Bind the execution context with RunspaceConfiguration. // This has the side effect of initializing cmdlet cache and providers from runspace configuration. if (runspaceConfiguration != null) { runspaceConfiguration.Bind(Context); } else { // Load the iss, resetting everything to it's defaults... iss.Bind(Context, /*updateOnly*/ false); } InitialSessionState.SetSessionStateDrive(Context, true); }
private PowerShell GetPowershell(InitialSessionState initialSessionState) { return(PowerShell.Create(initialSessionState)); }
/// <summary> /// Gets a list of matching commands /// </summary> /// <param name="pattern">Command pattern.</param> /// <param name="commandOrigin"></param> /// <param name="context"></param> /// <param name="rediscoverImportedModules"></param> /// <param name="moduleVersionRequired"></param> /// <returns></returns> internal static IEnumerable <CommandInfo> GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false) { // Otherwise, if it had wildcards, just return the "AvailableCommand" // type of command info. WildcardPattern commandPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Get-Module"); PSModuleAutoLoadingPreference moduleAutoLoadingPreference = CommandDiscovery.GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference"); if ((moduleAutoLoadingPreference != PSModuleAutoLoadingPreference.None) && ((commandOrigin == CommandOrigin.Internal) || ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public)) ) ) { foreach (string modulePath in GetDefaultAvailableModuleFiles(isForAutoDiscovery: false, context)) { // Skip modules that have already been loaded so that we don't expose private commands. string moduleName = Path.GetFileNameWithoutExtension(modulePath); List <PSModuleInfo> modules = context.Modules.GetExactMatchModules(moduleName, all: false, exactMatch: true); PSModuleInfo tempModuleInfo = null; if (modules.Count != 0) { // 1. We continue to the next module path if we don't want to re-discover those imported modules // 2. If we want to re-discover the imported modules, but one or more commands from the module were made private, // then we don't do re-discovery if (!rediscoverImportedModules || modules.Exists(module => module.ModuleHasPrivateMembers)) { continue; } if (modules.Count == 1) { PSModuleInfo psModule = modules[0]; tempModuleInfo = new PSModuleInfo(psModule.Name, psModule.Path, context: null, sessionState: null); tempModuleInfo.SetModuleBase(psModule.ModuleBase); foreach (KeyValuePair <string, CommandInfo> entry in psModule.ExportedCommands) { if (commandPattern.IsMatch(entry.Value.Name)) { CommandInfo current = null; switch (entry.Value.CommandType) { case CommandTypes.Alias: current = new AliasInfo(entry.Value.Name, definition: null, context); break; case CommandTypes.Function: current = new FunctionInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context); break; case CommandTypes.Filter: current = new FilterInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context); break; case CommandTypes.Configuration: current = new ConfigurationInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context); break; case CommandTypes.Cmdlet: current = new CmdletInfo(entry.Value.Name, implementingType: null, helpFile: null, PSSnapin: null, context); break; default: Dbg.Assert(false, "cannot be hit"); break; } current.Module = tempModuleInfo; yield return(current); } } continue; } } string moduleShortName = System.IO.Path.GetFileNameWithoutExtension(modulePath); IDictionary <string, CommandTypes> exportedCommands = AnalysisCache.GetExportedCommands(modulePath, testOnly: false, context); if (exportedCommands == null) { continue; } tempModuleInfo = new PSModuleInfo(moduleShortName, modulePath, sessionState: null, context: null); if (InitialSessionState.IsEngineModule(moduleShortName)) { tempModuleInfo.SetModuleBase(Utils.DefaultPowerShellAppBase); } //moduleVersionRequired is bypassed by FullyQualifiedModule from calling method. This is the only place where guid will be involved. if (moduleVersionRequired && modulePath.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) { tempModuleInfo.SetVersion(ModuleIntrinsics.GetManifestModuleVersion(modulePath)); tempModuleInfo.SetGuid(ModuleIntrinsics.GetManifestGuid(modulePath)); } foreach (KeyValuePair <string, CommandTypes> pair in exportedCommands) { string commandName = pair.Key; CommandTypes commandTypes = pair.Value; if (commandPattern.IsMatch(commandName)) { bool shouldExportCommand = true; // Verify that we don't already have it represented in the initial session state. if ((context.InitialSessionState != null) && (commandOrigin == CommandOrigin.Runspace)) { foreach (SessionStateCommandEntry commandEntry in context.InitialSessionState.Commands[commandName]) { string moduleCompareName = null; if (commandEntry.Module != null) { moduleCompareName = commandEntry.Module.Name; } else if (commandEntry.PSSnapIn != null) { moduleCompareName = commandEntry.PSSnapIn.Name; } if (string.Equals(moduleShortName, moduleCompareName, StringComparison.OrdinalIgnoreCase)) { if (commandEntry.Visibility == SessionStateEntryVisibility.Private) { shouldExportCommand = false; } } } } if (shouldExportCommand) { if ((commandTypes & CommandTypes.Alias) == CommandTypes.Alias) { yield return(new AliasInfo(commandName, null, context) { Module = tempModuleInfo }); } if ((commandTypes & CommandTypes.Cmdlet) == CommandTypes.Cmdlet) { yield return(new CmdletInfo(commandName, implementingType: null, helpFile: null, PSSnapin: null, context: context) { Module = tempModuleInfo }); } if ((commandTypes & CommandTypes.Function) == CommandTypes.Function) { yield return(new FunctionInfo(commandName, ScriptBlock.EmptyScriptBlock, context) { Module = tempModuleInfo }); } if ((commandTypes & CommandTypes.Configuration) == CommandTypes.Configuration) { yield return(new ConfigurationInfo(commandName, ScriptBlock.EmptyScriptBlock, context) { Module = tempModuleInfo }); } } } } } } }
#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); // 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 { #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); } } System.Environment.FailFast(e.Message, e); } catch (Exception e) { System.Environment.FailFast(e.Message, e); } return(exitCode); }
public PSScriptExecutor(string pathToScripts, string[] modulesToLoad, string psExecutionPolicy, string psOutputDelimiter) { this.pathToScripts = pathToScripts; this.modulesToLoad = modulesToLoad; this.psExecutionPolicy = psExecutionPolicy; this.psOutputDelimiter = psOutputDelimiter; // Initialise PowerShell Runspace and preload necessary modules. // See here: http://stackoverflow.com/a/17071164 // See here: http://nivot.org/blog/post/2010/05/03/PowerShell20DeveloperEssentials1InitializingARunspaceWithAModule InitialSessionState initialSession = InitialSessionState.CreateDefault2(); if (modulesToLoad != null && modulesToLoad.Length > 0) { initialSession.ImportPSModule(modulesToLoad); } if (psExecutionPolicy != "None") { PSScriptInvoker.logInfo("Setting custom PowerShell Execution Policy: " + psExecutionPolicy); switch (psExecutionPolicy) { case "AllSigned": initialSession.ExecutionPolicy = ExecutionPolicy.AllSigned; break; case "Bypass": initialSession.ExecutionPolicy = ExecutionPolicy.Bypass; break; case "RemoteSigned": initialSession.ExecutionPolicy = ExecutionPolicy.RemoteSigned; break; case "Restricted": initialSession.ExecutionPolicy = ExecutionPolicy.Restricted; break; case "Undefined": initialSession.ExecutionPolicy = ExecutionPolicy.Undefined; break; case "Unrestricted": initialSession.ExecutionPolicy = ExecutionPolicy.Unrestricted; break; default: PSScriptInvoker.logWarning("Given custom PowerShell Execution Policy is unknown: " + psExecutionPolicy + ". Only one of the following custom policies is allowed: AllSigned, Bypass, RemoteSigned, Restricted, Undefined, Unrestricted. Set to policy 'Default'."); initialSession.ExecutionPolicy = ExecutionPolicy.Default; break; } } // This loads the InitialStateSession for all instances // Note you can set the minimum and maximum number of runspaces as well // Note that without setting the minimum and maximum number of runspaces, it will use 1 as default for both: // https://docs.microsoft.com/en-us/dotnet/api/system.management.automation.runspaces.runspacefactory.createrunspacepool?view=powershellsdk-1.1.0 // See here: https://stackoverflow.com/a/24358855 runspacePool = RunspaceFactory.CreateRunspacePool(initialSession); runspacePool.SetMinRunspaces(MIN_RUNSPACES); runspacePool.SetMaxRunspaces(int.MaxValue); runspacePool.ThreadOptions = PSThreadOptions.UseNewThread; runspacePool.Open(); }
/// <summary> /// Constructor. /// </summary> /// <param name="name"></param> /// <param name="command"></param> /// <param name="sb"></param> /// <param name="filePath"></param> /// <param name="initSb"></param> /// <param name="argumentList"></param> /// <param name="inputObject"></param> /// <param name="psCmdlet"></param> /// <param name="currentLocationPath"></param> /// <param name="streamingHost"></param> public ThreadJob( string name, string command, ScriptBlock sb, string filePath, ScriptBlock initSb, object[] argumentList, PSObject inputObject, PSCmdlet psCmdlet, string currentLocationPath, PSHost streamingHost) : base(command, name) { _sb = sb; _filePath = filePath; _initSb = initSb; _argumentList = argumentList; _input = new PSDataCollection <object>(); if (inputObject != null) { _input.Add(inputObject); } _output = new PSDataCollection <PSObject>(); _streamingHost = streamingHost; _currentLocationPath = currentLocationPath; this.PSJobTypeName = "ThreadJob"; // Get script block to run. if (!string.IsNullOrEmpty(_filePath)) { _sb = GetScriptBlockFromFile(_filePath, psCmdlet); if (_sb == null) { throw new InvalidOperationException(Properties.Resources.CannotParseScriptFile); } } else if (_sb == null) { throw new PSArgumentNullException(Properties.Resources.NoScriptToRun); } // Create Runspace/PowerShell object and state callback. // The job script/command will run in a separate thread associated with the Runspace. var iss = InitialSessionState.CreateDefault2(); // Determine session language mode for Windows platforms WarningRecord lockdownWarning = null; if (Environment.OSVersion.Platform.ToString().Equals("Win32NT", StringComparison.OrdinalIgnoreCase)) { bool enforceLockdown = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce); if (enforceLockdown && !string.IsNullOrEmpty(_filePath)) { // If script source is a file, check to see if it is trusted by the lock down policy enforceLockdown = (SystemPolicy.GetLockdownPolicy(_filePath, null) == SystemEnforcementMode.Enforce); if (!enforceLockdown && (_initSb != null)) { // Even if the script file is trusted, an initialization script cannot be trusted, so we have to enforce // lock down. Otherwise untrusted script could be run in FullLanguage mode along with the trusted file script. enforceLockdown = true; lockdownWarning = new WarningRecord( string.Format( CultureInfo.InvariantCulture, Properties.Resources.CannotRunTrustedFileInFL, _filePath)); } } iss.LanguageMode = enforceLockdown ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage; } if (_streamingHost != null) { _rs = RunspaceFactory.CreateRunspace(_streamingHost, iss); } else { _rs = RunspaceFactory.CreateRunspace(iss); } _ps = PowerShell.Create(); _ps.Runspace = _rs; _ps.InvocationStateChanged += (sender, psStateChanged) => { var newStateInfo = psStateChanged.InvocationStateInfo; // Update Job state. switch (newStateInfo.State) { case PSInvocationState.Running: SetJobState(JobState.Running); break; case PSInvocationState.Stopped: SetJobState(JobState.Stopped, newStateInfo.Reason, disposeRunspace: true); break; case PSInvocationState.Failed: SetJobState(JobState.Failed, newStateInfo.Reason, disposeRunspace: true); break; case PSInvocationState.Completed: if (_runningInitScript) { // Begin running main script. _runningInitScript = false; RunScript(); } else { SetJobState(JobState.Completed, newStateInfo.Reason, disposeRunspace: true); } break; } }; // Get any using variables. var usingAsts = _sb.Ast.FindAll(ast => ast is UsingExpressionAst, searchNestedScriptBlocks: true).Cast <UsingExpressionAst>(); if (usingAsts != null && usingAsts.FirstOrDefault() != null) { // Get using variables as dictionary, since we now only support PowerShell version 5.1 and greater _usingValuesMap = GetUsingValuesAsDictionary(usingAsts, psCmdlet); } // Hook up data streams. this.Output = _output; this.Output.EnumeratorNeverBlocks = true; this.Error = _ps.Streams.Error; this.Error.EnumeratorNeverBlocks = true; this.Progress = _ps.Streams.Progress; this.Progress.EnumeratorNeverBlocks = true; this.Verbose = _ps.Streams.Verbose; this.Verbose.EnumeratorNeverBlocks = true; this.Warning = _ps.Streams.Warning; this.Warning.EnumeratorNeverBlocks = true; if (lockdownWarning != null) { this.Warning.Add(lockdownWarning); } this.Debug = _ps.Streams.Debug; this.Debug.EnumeratorNeverBlocks = true; this.Information = _ps.Streams.Information; this.Information.EnumeratorNeverBlocks = true; // Create the JobManager job definition and job specification, and add to the JobManager. ThreadJobDefinition = new JobDefinition(typeof(ThreadJobSourceAdapter), "", Name); Dictionary <string, object> parameterCollection = new Dictionary <string, object>(); parameterCollection.Add("NewJob", this); var jobSpecification = new JobInvocationInfo(ThreadJobDefinition, parameterCollection); var newJob = psCmdlet.JobManager.NewJob(jobSpecification); System.Diagnostics.Debug.Assert(newJob == this, "JobManager must return this job"); }
public static async Task <ReturnModel> QueryWmi(this QueryWmiModel model) { try { ReturnModel returnModel = new ReturnModel(); InitialSessionState iss = InitialSessionState.CreateDefault(); iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted; using (Runspace rs = RunspaceFactory.CreateRunspace(iss)) { rs.Open(); var script = string.Empty; if (model.isRemoteConnection) { script = await("PowerShellAPIFramework.Core.Scripts.query-wmi-remote.ps1").GetTextFromEmbeddedResource(); } else { script = await("PowerShellAPIFramework.Core.Scripts.query-wmi.ps1").GetTextFromEmbeddedResource(); } Command queryWmi = new Command(script, true); queryWmi.Parameters.Add("query", model.query); queryWmi.Parameters.Add("computername", model.computername); queryWmi.Parameters.Add("wmiNamespace", model.wmiNamespace); if (model.isRemoteConnection) { queryWmi.Parameters.Add("credential", new PSCredential(model.username, model.securePassword)); } using (PowerShell ps = PowerShell.Create()) { ps.Runspace = rs; ps.Commands.AddCommand(queryWmi); var psResults = ps.Invoke(); if (ps.HadErrors) { if (ps.Streams.Error.Count > 0) { var exceptions = new StringBuilder(); foreach (var error in ps.Streams.Error) { exceptions.AppendLine(error.Exception.GetExceptionMessageChain()); } throw new Exception(exceptions.ToString()); } } else { foreach (var result in psResults) { if (psResults.IndexOf(result) == 0) { returnModel.properties = result.Properties.Select(x => x.Name).ToList(); } var resultModel = new ResultModel { propertyValues = result.Properties.Select(x => new PropertyValueModel { property = x.Name, value = x.Value }).AsEnumerable() }; returnModel.results.Add(resultModel); } } } } return(returnModel); } catch (Exception ex) { throw new Exception(ex.GetExceptionMessageChain()); } }