internal static void LoadISSWithModuleDetails(ModuleDetails moduleDetails, InitialSessionState iss) { PSSnapInException pSSnapInException = new PSSnapInException(); if (moduleDetails.Functions.Count > 0) { iss.Commands.Add(moduleDetails.Functions.FirstOrDefault()); } if (moduleDetails.PSModule.Length > 0) { iss.ImportPSModule(new string[] { moduleDetails.PSModule }); } if (moduleDetails.PSSnapIn.Length > 0) { iss.ImportPSSnapIn(moduleDetails.PSSnapIn, out pSSnapInException); } }
/// <summary> /// This sample uses an initial session state to create a runspace. The sample /// invokes a command from a PowerShell snap-in present in the console file. /// </summary> /// <param name="args">Parameter not used.</param> /// <remarks> /// This sample assumes that user has the GetProcessSample01.dll that is produced /// by the GetProcessSample01 sample copied to the current directory. /// This sample demonstrates the following: /// 1. Creating a default initial session state. /// 2. Creating a runspace using the default initial session state. /// 3. Creating a PowerShell object that uses the runspace. /// 4. Adding the get-proc cmdlet to the PowerShell object from a /// snap-in. /// 5. Using PSObject objects to extract and display properties from /// the objects returned by the cmdlet. /// </remarks> private static void Main(string[] args) { // Create the default initial session state. The default initial // session state contains all the elements provided by Windows PowerShell. InitialSessionState iss = InitialSessionState.CreateDefault(); PSSnapInException warning; iss.ImportPSSnapIn("GetProcPSSnapIn01", out warning); // Create a runspace. Notice that no PSHost object is supplied to the // CreateRunspace method so the default host is used. See the Host // samples for more information on creating your own custom host. using (Runspace myRunSpace = RunspaceFactory.CreateRunspace(iss)) { myRunSpace.Open(); // Create a PowerShell object. using (PowerShell powershell = PowerShell.Create()) { // Add the Cmdlet and specify the runspace. powershell.AddCommand("GetProcPSSnapIn01\\get-proc"); powershell.Runspace = myRunSpace; // Run the cmdlet synchronously. Collection <PSObject> results = powershell.Invoke(); Console.WriteLine("Process HandleCount"); Console.WriteLine("--------------------------------"); // Display the results. foreach (PSObject result in results) { Console.WriteLine( "{0,-20} {1}", result.Members["ProcessName"].Value, result.Members["HandleCount"].Value); } } // Close the runspace to release any resources. myRunSpace.Close(); } System.Console.WriteLine("Hit any key to exit..."); System.Console.ReadKey(); }
/// <summary> /// Executes the specified PowerShell script. /// </summary> /// <param name="scriptText"></param> /// <returns></returns> public static Collection <PSObject> ExecutePowerShellScript(string scriptText) { InitialSessionState iss = InitialSessionState.CreateDefault(); PSSnapInException warning; iss.ImportPSSnapIn("Microsoft.SharePoint.PowerShell", out warning); Collection <PSObject> results; // create Powershell runspace using (var runspace = RunspaceFactory.CreateRunspace(iss)) { // open it runspace.Open(); try { // create a pipeline and feed it the script text var pipeline = runspace.CreatePipeline(); pipeline.Commands.AddScript(scriptText); pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); try { // execute the script results = pipeline.Invoke(); } catch (Exception ex) { BaristaDiagnosticsService.Local.LogException(ex, BaristaDiagnosticCategory.PowerShell, "Unexpected Error while executing PowerShell Script:"); throw; } } finally { runspace.Close(); } } //Return the results. return(results); }
/// <summary> /// This sample uses an InitialSessionState to create Runspace. It invokes /// a command from PowerShell snap-in present in the console file. /// </summary> /// <param name="args">Unused</param> /// <remarks> /// This sample assumes that user has the PowerShell binary module "GetProcessSample01.dll" /// produced in sample GetProcessSample01 copied to the current directory. /// /// This sample demonstrates the following: /// 1. Creating a default instance of InitialSessionState /// 2. Using the InitialSessionState to create a runspace /// 3. Create a pipeline with the get-proc cmdlet available in the PowerShell binary module /// 4. Using PSObject to extract and display properties from the objects /// returned by this command /// </remarks> static void Main(string[] args) { InitialSessionState iss = InitialSessionState.CreateDefault(); PSSnapInException warning; iss.ImportPSSnapIn("GetProcPSSnapIn01", out warning); // Create a runspace. // (Note that no PSHost instance is supplied to the CreateRunspace // function so the default PSHost implementation is used. See the // Hosting topics for more information on creating your own PSHost class.) Runspace myRunSpace = RunspaceFactory.CreateRunspace(iss); myRunSpace.Open(); // Create a PowerShell with get-proc command. PowerShell powershell = PowerShell.Create().AddCommand("GetProcPSSnapIn01\\get-proc"); powershell.Runspace = myRunSpace; Collection <PSObject> results = powershell.Invoke(); Console.WriteLine("Process HandleCount"); Console.WriteLine("--------------------------------"); // Print out each result object... foreach (PSObject result in results) { Console.WriteLine("{0,-20} {1}", result.Members["ProcessName"].Value, result.Members["HandleCount"].Value); } // Finally close the runspace // up any resources. myRunSpace.Close(); System.Console.WriteLine("Hit any key to exit..."); System.Console.ReadKey(); }
/// <summary> /// Create the Runspace pool. /// For remote runspaces, load the datatypes optionally to support serialization /// For local commands, load the modules and snapins required or requested /// </summary> /// <param name="commandInfo"></param> /// <param name="pSHost"></param> /// <param name="maxRunspaces"></param> /// <param name="debugStrings"></param> /// <param name="useRemotePS"></param> /// <param name="loadAllTypedata"></param> /// <param name="modules"></param> /// <param name="modulesPath"></param> /// <param name="snapIns"></param> /// <param name="variableEntries"></param> /// <returns></returns> internal static RunspacePool CreateRunspacePool(CommandInfo commandInfo, PSHost pSHost, int maxRunspaces, out List <string> debugStrings, PSSession useRemotePS, bool loadAllTypedata, string[] modules = null, string[] modulesPath = null, string[] snapIns = null, IList <SessionStateVariableEntry> variableEntries = null) { debugStrings = new List <string>(); RunspaceConnectionInfo runspaceConnectionInfo = null; Hashtable modulePrivatedata = commandInfo.Module?.PrivateData as Hashtable; ModuleDetails moduleDetails = GetModuleDetails(commandInfo, debugStrings); //special handling for remote PSsession commands if (moduleDetails.IsFromRemotingModule || useRemotePS != null) { if (useRemotePS != null) { debugStrings.Add("Using the supplied remote PSSession"); runspaceConnectionInfo = useRemotePS.Runspace.ConnectionInfo; } else { debugStrings.Add("Using remote PSSession to execute the command"); PSObject remotepSModule = ScriptBlock.Create( string.Format("Get-Module {0}", commandInfo.ModuleName)).InvokeReturnAsIs() as PSObject; if (remotepSModule.BaseObject is PSModuleInfo remotepSModuleInfo) { PSObject remotePs = ScriptBlock.Create( string.Format("Get-PSSession | Where-Object{{$_.state -eq 'opened' -and (\"{0}\").Contains($_.ComputerName)}} | Select-Object -First 1", remotepSModuleInfo.Description)).InvokeReturnAsIs() as PSObject; if (remotePs.BaseObject is PSSession remotePSSession) { runspaceConnectionInfo = remotePSSession.Runspace.ConnectionInfo; if (modules != null || modulesPath != null) { debugStrings.Add("Modules were specified to load, but they will not be loaded as the command supplied is from a remote PSSession"); } } else { debugStrings.Add(string.Format("Command - Get-PSSession | Where-Object{{$_.state -eq 'opened' -and (\"{0}\").Contains($_.ComputerName)}} " + "| Select-Object -First 1 - was ran to find the PSSession", remotepSModuleInfo.Description)); throw new Exception("Unable to find a PSSession to use. You may try passing the PSSession to use using Parameter -UseRemotePSSession"); } } } debugStrings.Add(string.Format("Using connection info {0}", runspaceConnectionInfo.ComputerName)); TypeTable typeTable = TypeTable.LoadDefaultTypeFiles(); if (loadAllTypedata) { Collection <PSObject> typeDatas = ScriptBlock.Create("Get-TypeData").Invoke(); foreach (PSObject typeData in typeDatas) { TypeData t = (TypeData)typeData.BaseObject; try { typeTable.AddType(t); debugStrings.Add(string.Format("Added typedata{0}", t.TypeName)); } catch (Exception e) { debugStrings.Add(string.Format("Unable to add typeData {0}. Error {1}", t.TypeName, e.Message)); } } } return(RunspaceFactory.CreateRunspacePool(1, Environment.ProcessorCount, runspaceConnectionInfo, pSHost, typeTable)); } InitialSessionState iss = InitialSessionState.CreateDefault2(); List <string> modulesToLoad = new List <String>(); List <string> snapInsToLoad = new List <string>(); PSSnapInException pSSnapInException = new PSSnapInException(); if (modules?.Count() > 0) { modulesToLoad.AddRange(modules); } if (snapIns?.Count() > 0) { snapInsToLoad.AddRange(snapIns); } //Populate ISS with the snapins and modules from the moduleDetails LoadISSWithModuleDetails(moduleDetails, iss); //Load user specified snapins and modules if (modules?.Count() > 0 && modules.Contains("All", StringComparer.OrdinalIgnoreCase)) { var modulesAvailable = ScriptBlock.Create("Get-Module -ListAvailable | Select-Object -ExpandProperty Name").Invoke(); modulesToLoad.AddRange(from module in modulesAvailable select module.BaseObject as string); debugStrings.Add(string.Format("Loaded all the available modules on this computer, {0} modules found", modulesToLoad.Count)); } if (modules?.Count() > 0 && modules.Contains("Loaded", StringComparer.OrdinalIgnoreCase)) { var modulesLoaded = ScriptBlock.Create("Get-Module | Select-Object -ExpandProperty Name").Invoke(); modulesToLoad.AddRange(from module in modulesLoaded select module.BaseObject as string); debugStrings.Add(string.Format("Loaded the modules loaded on current Runspace, {0} modules found", modulesLoaded.Count)); } debugStrings.Add("Loading Modules:"); debugStrings.AddRange(modulesToLoad); iss.ImportPSModule(modulesToLoad.ToArray()); snapInsToLoad.ForEach(s => iss.ImportPSSnapIn(s, out pSSnapInException)); if (variableEntries != null) { iss.Variables.Add(variableEntries); } return(RunspaceFactory.CreateRunspacePool(1, maxRunspaces, iss, pSHost)); }
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); } } } } } } }
private string ExecuteLocal(string ScriptPath, string ScriptCode, int HasParams, string TableAsString) { StringWriter sw = new StringWriter(); DataTable dt = new DataTable("resultSet"); dt.Columns.Add("Result", typeof(String)); try { if (string.IsNullOrEmpty(ScriptCode) == false) { ScriptCode = ScriptCode.Replace("\t", "\r\n"); } if (string.IsNullOrEmpty(ScriptPath) == false) { if (File.Exists(ScriptPath)) { ScriptCode = File.ReadAllText(ScriptPath); } else { throw new Exception("File not found"); } } InitialSessionState iss = InitialSessionState.CreateDefault(); PSSnapInException warning; string[] MyArray = ScriptCode.Split(new string[] { "\r\n" }, StringSplitOptions.None); foreach (string item in MyArray) { if (item.ToLower().Contains("add-pssnapin")) { iss.ImportPSSnapIn(item.Substring(item.ToLower().IndexOf("add-pssnapin") + 12).Trim(), out warning); ScriptCode = ScriptCode.Replace(item, ""); } } Collection <PSObject> results = null; using (PowerShellProcessInstance instance = new PowerShellProcessInstance(new Version(4, 0), null, null, false)) { using (var runspace = RunspaceFactory.CreateOutOfProcessRunspace(new TypeTable(new string[0]), instance)) { runspace.Open(); using (Pipeline pipeline = runspace.CreatePipeline()) { if (HasParams == 1 && string.IsNullOrEmpty(TableAsString) == false) { CommandParameter param; DataTable dtParams = new DataTable(); System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); using (MemoryStream stream = new MemoryStream()) { byte[] allBytes = enc.GetBytes(TableAsString); stream.Write(allBytes, 0, allBytes.Length); stream.Position = 0; dtParams.ReadXml(stream); } Command myCommand = new Command(ScriptCode, true); foreach (DataRow row in dtParams.Rows) { param = new CommandParameter(row[0].ToString(), row[1]); myCommand.Parameters.Add(param); } pipeline.Commands.Add(myCommand); pipeline.Commands.Add("Out-String"); } else { pipeline.Commands.AddScript(ScriptCode); pipeline.Commands.Add("Out-String"); } results = pipeline.Invoke(); } } } StringBuilder stbuilder = new StringBuilder(); bool isStartLine = true; string cmdResult = string.Empty; foreach (PSObject obj in results) { if (isStartLine) { cmdResult = ClearString(obj.ToString()); isStartLine = false; } else { cmdResult = obj.ToString(); } dt.Rows.Add(cmdResult); } } catch (Exception ex) { throw ex; } dt.WriteXml(sw, XmlWriteMode.WriteSchema, false); return(sw.ToString()); }
/// <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 } } }
/// <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); } } }
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); } } } } }