PowerShellHost.cs (3586B)
1 // ----------------------------------------------------------------------------- 2 // <copyright file="PowerShellHost.cs" company="Microsoft Corporation"> 3 // Copyright (c) Microsoft Corporation. Licensed under the MIT License. 4 // </copyright> 5 // ----------------------------------------------------------------------------- 6 7 namespace AppInstallerCLIE2ETests.PowerShell 8 { 9 using System; 10 using System.Collections; 11 using System.Management.Automation; 12 using System.Management.Automation.Runspaces; 13 using Microsoft.PowerShell; 14 using NUnit.Framework; 15 16 /// <summary> 17 /// Helper class to run powershell commands. 18 /// </summary> 19 internal class PowerShellHost : IDisposable 20 { 21 private readonly Runspace runspace = null; 22 23 private bool disposed = false; 24 25 /// <summary> 26 /// Initializes a new instance of the <see cref="PowerShellHost"/> class. 27 /// </summary> 28 public PowerShellHost() 29 { 30 InitialSessionState initialSessionState = InitialSessionState.CreateDefault(); 31 initialSessionState.ExecutionPolicy = ExecutionPolicy.Unrestricted; 32 33 this.runspace = RunspaceFactory.CreateRunspace(initialSessionState); 34 this.runspace.Open(); 35 this.VerifyErrorState(); 36 37 this.PowerShell = PowerShell.Create(this.runspace); 38 } 39 40 /// <summary> 41 /// Finalizes an instance of the <see cref="PowerShellHost"/> class. 42 /// </summary> 43 ~PowerShellHost() => this.Dispose(false); 44 45 /// <summary> 46 /// Gets PowerShell. 47 /// </summary> 48 public PowerShell PowerShell { get; private set; } = null; 49 50 /// <summary> 51 /// Dispose. 52 /// </summary> 53 public void Dispose() 54 { 55 this.Dispose(true); 56 GC.SuppressFinalize(this); 57 } 58 59 /// <summary> 60 /// Add module path. 61 /// </summary> 62 /// <param name="path">Path.</param> 63 public void AddModulePath(string path) 64 { 65 var newModulePath = this.PowerShell.Runspace.SessionStateProxy.PSVariable.GetValue("env:PSModulePath") + $";{path}"; 66 this.PowerShell.Runspace.SessionStateProxy.PSVariable.Set("env:PSModulePath", newModulePath); 67 } 68 69 /// <summary> 70 /// Protected implementation of dispose pattern. 71 /// </summary> 72 /// <param name="disposing">Dispose.</param> 73 protected virtual void Dispose(bool disposing) 74 { 75 if (!this.disposed) 76 { 77 if (disposing) 78 { 79 this.PowerShell.Dispose(); 80 this.runspace.Dispose(); 81 } 82 83 this.disposed = true; 84 } 85 } 86 87 /// <summary> 88 /// The most common error is that the module was not found. 89 /// </summary> 90 private void VerifyErrorState() 91 { 92 var errors = (ArrayList)this.runspace.SessionStateProxy.PSVariable.GetValue("Error"); 93 94 if (errors.Count > 0) 95 { 96 string errorMessage = "PSVariable Error:"; 97 foreach (var error in errors) 98 { 99 errorMessage += Environment.NewLine + ((ErrorRecord)error).Exception.Message; 100 } 101 102 TestContext.Error.WriteLine(errorMessage); 103 throw new Exception(errorMessage); 104 } 105 } 106 } 107 }