public Runspace CreateLocal()
        {
            InitialSessionState initial = InitialSessionState.CreateDefault();

            initial.ExecutionPolicy = ExecutionPolicy.Unrestricted;

            initial.ImportPSModule(new[] { "SqlServer" });
            initial.ImportPSModule(new[] { "Sifon" });
            return(RunspaceFactory.CreateRunspace(initial));
        }
Esempio n. 2
0
        private System.Management.Automation.PowerShell CreatePowerShellObject(PSHost host, string modulePath)
        {
            System.Management.Automation.PowerShell ps = null;
            try
            {
                //loading SHiPS module
                _sessionstate.ImportPSModule(new[] { SHiPSModule });

                //loading dsl module
                if (!string.IsNullOrWhiteSpace(modulePath))
                {
                    _sessionstate.ImportPSModule(new[] { modulePath });
                }
                _runspace = RunspaceFactory.CreateRunspace(host, _sessionstate);

                if (_runspace == null)
                {
                    return(null);
                }
                else
                {
                    _runspace.Open();
                    var error = _runspace.SessionStateProxy.PSVariable.GetValue("Error") as ArrayList;
                    if (error != null && error.Count > 0)
                    {
                        _provider.ThrowTerminatingError(error[0] as ErrorRecord);
                        return(null);
                    }
                    ps = System.Management.Automation.PowerShell.Create();

                    //Cannot use ps.Runspace = Runspace.DefaultRunspace, it will give you an error
                    //Pipelines cannot be run concurrently
                    ps.Runspace = _runspace;
                    return(ps);
                }
            }
            catch (Exception)
            {
                // didn't create or import correctly.
                if (ps != null)
                {
                    ps.Dispose();
                }
                if (_runspace != null)
                {
                    _runspace.Close();
                }

                throw;
            }
        }
Esempio n. 3
0
        // Tried too, but didn't work (-> Runspace & Pipeline on Runspace):
        //
        //  ps.AddScript("Import-Module ExchangeOnlineManagement");
        //  ps.Invoke();
        //
        //  ps.AddCommand("Import-Module")
        //	     .AddParameter("Name", "ExchangeOnlineManagement");
        public (string, string) InMemoryPfxAuthN()
        {
            if (null == Certificate)
            {
                throw new ArgumentException("Did you use the wrong ctor for this PoC class?");
            }

            // Stage #1

            // netcore31/5 Web App: Cannot load PowerShell snap-in Microsoft.PowerShell.Diagnostics because of the following error: Could not load file or assembly
            //              ==> reason: SMA is not enough... need PS SDK NuGet package
            InitialSessionState iss = InitialSessionState.CreateDefault();

            iss.ExecutionPolicy = Microsoft.PowerShell.ExecutionPolicy.Unrestricted;

            iss.ImportPSModule(new string[] { "ExchangeOnlineManagement" });
            using (var exchangeRunspace = RunspaceFactory.CreateRunspace(iss))             // Using stmts gehen nur in Core... Dreck
            {
                exchangeRunspace.Open();

                using (var pipeLine = exchangeRunspace.CreatePipeline())
                {
                    var connectCmd = new Command("Connect-ExchangeOnline");
                    connectCmd.Parameters.Add("AppId", AppId);
                    connectCmd.Parameters.Add("Organization", Organization);
                    connectCmd.Parameters.Add("Certificate", Certificate);

                    pipeLine.Commands.Add(connectCmd);

                    // NetCore Ex #1: Could not load file or assembly 'Microsoft.Identity.Client, Version=4.23.0.0
                    //              ==> reason: Azure.Identity transitively includes 4.18, thus: manually add 4.23 package
                    // NetCore Ex #2: The certificate certificate does not have a private key.
                    //              ==> reason: KV... you need to read the certificate as secret to get the private key included
                    // NetCore 5 Ex: NotSupportedException: BinaryFormatter serialization and deserialization are disabled within this application. See https://aka.ms/binaryformatter for more information.
                    //              ==> reason: see csproj
                    pipeLine.Invoke();
                    if (pipeLine.Error != null && pipeLine.Error.Count > 0)
                    {
                        // check error
                    }
                }

                // Stage #2
                using (var ps = PowerShell.Create())
                {
                    ps.Runspace = exchangeRunspace;

                    ps.Commands.AddCommand("Get-EXOMailBox")
                    .AddParameter("ResultSize", "unlimited");

                    // ps.Commands.AddCommand("Get-MailBox");

                    // NetFw Ex #1: System.Management.Automation.CmdletInvocationException System event notifications are not supported under the current context.Server processes, for example, may not support global system event notifications.
                    //              ==> reason: Get-EXOMailBox (tested w. System.Management.Automation from GAC - new cmdlets only works with netcore31++)
                    List <PSObject> results = ps.Invoke().ToList();

                    return(FlattenErrors(ps), ResultsToSimpleString(results));
                }
            }
        }
        static void Main(string[] args)
        {
            InitialSessionState initial = InitialSessionState.CreateDefault();

            String[] modules = { "DnsClient" };
            initial.ImportPSModule(modules);
            Runspace runspace = RunspaceFactory.CreateRunspace(initial);

            runspace.Open();
            RunspaceInvoke invoker = new RunspaceInvoke(runspace);

            Collection <PSObject> results = invoker.Invoke("Resolve-DnsName 'localhost'");

            runspace.Close();

            // convert the script result into a single string

            StringBuilder stringBuilder = new StringBuilder();

            foreach (PSObject obj in results)
            {
                foreach (PSMemberInfo m in obj.Members)
                {
                    stringBuilder.AppendLine(m.Name + ":");
                    stringBuilder.AppendLine(m.Value.ToString());
                }
            }

            Console.WriteLine(stringBuilder.ToString());
            Console.ReadKey();
        }
        public override ICommandStatus StopCollection()
        {
            CommandStatus status = new CommandStatus();

            status.CommandType = CommandType.IISCollectionStop;
            try
            {
                using (PowerShell PowerShellInstance = PowerShell.Create())
                {
                    InitialSessionState session = InitialSessionState.CreateDefault();
                    session.ImportPSModule(new string[] { IntellitracePSModuleNameAndPath });
                    Runspace runspace = RunspaceFactory.CreateRunspace(session);
                    runspace.Open();

                    PowerShellInstance.Runspace = runspace;
                    PowerShellInstance.Commands.AddCommand(@"Stop-IntelliTraceCollection");
                    PowerShellInstance.Commands.AddParameter("Confirm", false);
                    PowerShellInstance.Commands.AddParameter("ApplicationPool", this.AppPoolName);

                    var results = PowerShellInstance.Invoke();
                }
                status.Success = true;
            }
            catch (Exception ex)
            {
                status.Success     = false;
                status.ErrorMesage = ex.Message;
            }
            return(status);
        }
Esempio n. 6
0
        public List <ExternalRule> GetExternalRule(string[] moduleNames)
        {
            List <ExternalRule> rules = new List <ExternalRule>();

            if (moduleNames == null)
            {
                return(rules);
            }

            // Converts module path to module name.
            foreach (string moduleName in moduleNames)
            {
                string shortModuleName = string.Empty;

                // Imports modules by using full path.
                InitialSessionState state = InitialSessionState.CreateDefault2();
                state.ImportPSModule(new string[] { moduleName });

                using (System.Management.Automation.PowerShell posh =
                           System.Management.Automation.PowerShell.Create(state))
                {
                    string script = string.Format(CultureInfo.CurrentCulture, "Get-Module -Name '{0}' -ListAvailable", moduleName);
                    shortModuleName = posh.AddScript(script).Invoke <PSModuleInfo>().First().Name;

                    // Invokes Update-Help for this module
                    // Required since when invoking Get-Help later on, the cmdlet prompts for Update-Help interactively
                    // By invoking Update-Help first, Get-Help will not prompt for downloading help later
                    script = string.Format(CultureInfo.CurrentCulture, "Update-Help -Module '{0}' -Force", shortModuleName);
                    posh.AddScript(script).Invoke();

                    // Invokes Get-Command and Get-Help for each functions in the module.
                    script = string.Format(CultureInfo.CurrentCulture, "Get-Command -Module '{0}'", shortModuleName);
                    var psobjects = posh.AddScript(script).Invoke();

                    foreach (PSObject psobject in psobjects)
                    {
                        posh.Commands.Clear();

                        FunctionInfo      funcInfo = (FunctionInfo)psobject.ImmediateBaseObject;
                        ParameterMetadata param    = funcInfo.Parameters.Values
                                                     .First <ParameterMetadata>(item => item.Name.EndsWith("ast", StringComparison.OrdinalIgnoreCase) ||
                                                                                item.Name.EndsWith("token", StringComparison.OrdinalIgnoreCase));

                        //Only add functions that are defined as rules.
                        if (param != null)
                        {
                            script = string.Format(CultureInfo.CurrentCulture, "(Get-Help -Name {0}).Description | Out-String", funcInfo.Name);
                            string desc = posh.AddScript(script).Invoke()[0].ImmediateBaseObject.ToString()
                                          .Replace("\r\n", " ").Trim();

                            rules.Add(new ExternalRule(funcInfo.Name, funcInfo.Name, desc, param.Name, param.ParameterType.FullName,
                                                       funcInfo.ModuleName, funcInfo.Module.Path));
                        }
                    }
                }
            }

            return(rules);
        }
Esempio n. 7
0
        private void ImportTestInvokeScriptCmdlet()
        {
            InitialSessionState sessionState = InitialSessionState.Create();
            string fileName = typeof(InvokeScriptTests).Assembly.Location;

            sessionState.ImportPSModule(new string[] { fileName });
            TestHost.InitialSessionState = sessionState;
        }
Esempio n. 8
0
        public void LoadCmdletHelpers()
        {
            InitialSessionState sessionState = InitialSessionState.Create();
            string fileName = typeof(InitialSessionStateTests).Assembly.Location;

            sessionState.ImportPSModule(new string[] { fileName });
            TestHost.InitialSessionState = sessionState;
        }
        public void LoadCmdletHelpers()
        {
            InitialSessionState sessionState = InitialSessionState.CreateDefault();
            string fileName = typeof(VerboseCommonParameterTests).Assembly.Location;

            sessionState.ImportPSModule(new string[] { fileName });
            TestHost.InitialSessionState = sessionState;
        }
        // See the _ps_user_lookup method for demonstration of using this method
        public static Runspace new_runspace()
        {
            InitialSessionState init_state = InitialSessionState.CreateDefault();

            init_state.ThreadOptions = PSThreadOptions.UseCurrentThread;
            init_state.ImportPSModule(new[] { "ActiveDirectory", "C:\\ps_modules\\disable_user.psm1" });
            return(RunspaceFactory.CreateRunspace(init_state));
        }
Esempio n. 11
0
        private void ImportModule()
        {
            InitialSessionState initial = InitialSessionState.CreateDefault();
            string assemblyPath         = Path.Combine(Environment.CurrentDirectory, @"..\..\..\..\src\PackageManagement.PowerShellCmdlets\bin\debug\NuGet.PackageManagement.PowerShellCmdlets.dll");

            initial.ImportPSModule(new string[] { assemblyPath });
            _runSpace = RunspaceFactory.CreateRunspace(initial);
            _runSpace.Open();
        }
        /// <summary>
        /// Runs Get-MsolUser command and returns resulted data.
        /// </summary>
        /// <returns></returns>
        private Collection <PSObject> ExcutePowershellCommands()
        {
            try
            {
                Collection <PSObject> userList = null;
                // Create Initial Session State for runspace.
                InitialSessionState initialSession = InitialSessionState.CreateDefault();
                initialSession.ImportPSModule(new[] { "MSOnline" });
                // Create credential object.
                SecureString securePass = new SecureString();

                foreach (char secureChar in ConfigurationManager.AppSettings["Password"].ToString())
                {
                    securePass.AppendChar(secureChar);
                }
                PSCredential credential = new PSCredential(ConfigurationManager.AppSettings["UserID"].ToString(), securePass);
                // Create command to connect office 365.
                Command connectCommand = new Command("Connect-MsolService");
                connectCommand.Parameters.Add((new CommandParameter("Credential", credential)));
                // Create command to get office 365 users.
                Command getUserCommand = new Command("Get-MsolUser");
                using (Runspace psRunSpace = RunspaceFactory.CreateRunspace(initialSession))
                {
                    // Open runspace.
                    psRunSpace.Open();

                    //Iterate through each command and runs it.
                    foreach (var com in new Command[] { connectCommand, getUserCommand })
                    {
                        var pipe = psRunSpace.CreatePipeline();
                        pipe.Commands.Add(com);
                        // Run command and generate results and errors (if any).
                        Collection <PSObject> results = pipe.Invoke();
                        var error = pipe.Error.ReadToEnd();
                        if (error.Count > 0 && com == connectCommand)
                        {
                            return(null);
                        }
                        if (error.Count > 0 && com == getUserCommand)
                        {
                            return(null);
                        }
                        else
                        {
                            userList = results;
                        }
                    }
                    // Close the runspace.
                    psRunSpace.Close();
                }
                return(userList);
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Execute Get-MsolAccountSku command and returns resulted data.
        /// </summary>
        /// <returns></returns>
        private Collection <PSObject> ExcutePowershellCommands()
        {
            try
            {
                Collection <PSObject> licenseList = null;
                // Create Initial Session State for runspace.
                InitialSessionState initialSession = InitialSessionState.CreateDefault();
                initialSession.ImportPSModule(new[] { "MSOnline" });
                // Create credential object.
                PSCredential credential = new PSCredential(UserCredential.UserName, UserCredential.Password);
                // Create command to connect office 365.
                Command connectCommand = new Command("Connect-MsolService");
                connectCommand.Parameters.Add((new CommandParameter("Credential", credential)));
                // Create command to get office 365 users.
                Command getLicenseCommand = new Command("Get-MsolAccountSku");
                using (Runspace psRunSpace = RunspaceFactory.CreateRunspace(initialSession))
                {
                    // Open runspace.
                    psRunSpace.Open();

                    //Iterate through each command and executes it.
                    foreach (var com in new Command[] { connectCommand, getLicenseCommand })
                    {
                        var pipe = psRunSpace.CreatePipeline();
                        pipe.Commands.Add(com);
                        // Execute command and generate results and errors (if any).
                        Collection <PSObject> results = pipe.Invoke();
                        var error = pipe.Error.ReadToEnd();
                        if (error.Count > 0 && com == connectCommand)
                        {
                            MessageBox.Show(error[0].ToString(), "Problem in login");
                            this.Close();
                            return(null);
                        }
                        if (error.Count > 0 && com == getLicenseCommand)
                        {
                            MessageBox.Show(error[0].ToString(), "Problem in getting licenses");
                            this.Close();
                            return(null);
                        }
                        else
                        {
                            licenseList = results;
                        }
                    }
                    // Close the runspace.
                    psRunSpace.Close();
                }
                return(licenseList);
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Create a new runspace pool around a PSScriptAnalyzer module for asynchronous script analysis tasks.
        /// This looks for the latest version of PSScriptAnalyzer on the path and loads that.
        /// </summary>
        /// <returns>A runspace pool with PSScriptAnalyzer loaded for running script analysis tasks.</returns>
        private static RunspacePool CreatePssaRunspacePool(out PSModuleInfo pssaModuleInfo)
        {
            using (var ps = System.Management.Automation.PowerShell.Create())
            {
                // Run `Get-Module -ListAvailable -Name "PSScriptAnalyzer"`
                ps.AddCommand("Get-Module")
                .AddParameter("ListAvailable")
                .AddParameter("Name", PSSA_MODULE_NAME);

                try
                {
                    using (PSModulePathPreserver.Take())
                    {
                        // Get the latest version of PSScriptAnalyzer we can find
                        pssaModuleInfo = ps.Invoke <PSModuleInfo>()?
                                         .OrderByDescending(moduleInfo => moduleInfo.Version)
                                         .FirstOrDefault();
                    }
                }
                catch (Exception e)
                {
                    throw new FileNotFoundException("Unable to find PSScriptAnalyzer module on the module path", e);
                }

                if (pssaModuleInfo == null)
                {
                    throw new FileNotFoundException("Unable to find PSScriptAnalyzer module on the module path");
                }

                // Now that we know where the PSScriptAnalyzer we want to use is,
                // create a base session state with PSScriptAnalyzer loaded
#if DEBUG
                InitialSessionState sessionState = Environment.GetEnvironmentVariable("PSES_TEST_USE_CREATE_DEFAULT") == "1"
                    ? InitialSessionState.CreateDefault()
                    : InitialSessionState.CreateDefault2();
#else
                InitialSessionState sessionState = InitialSessionState.CreateDefault2();
#endif

                sessionState.ImportPSModule(new [] { pssaModuleInfo.ModuleBase });

                RunspacePool runspacePool = RunspaceFactory.CreateRunspacePool(sessionState);

                runspacePool.SetMaxRunspaces(1);
                runspacePool.ThreadOptions = PSThreadOptions.ReuseThread;

                // Open the runspace pool here so we can deterministically handle the PSModulePath change issue
                using (PSModulePathPreserver.Take())
                {
                    runspacePool.Open();
                }

                return(runspacePool);
            }
        }
Esempio n. 15
0
        public void ImportPSModuleAddsModule()
        {
            InitialSessionState sessionState = InitialSessionState.CreateDefault();
            string fileName = @"c:\MyCmdlets\MyCmdlet.dll";

            sessionState.ImportPSModule(new string[] { fileName });

            ModuleSpecification moduleSpec = sessionState.Modules[0];

            Assert.AreEqual(fileName, moduleSpec.Name);
        }
Esempio n. 16
0
        public MsPowerShellHost(string[] modules)
        {
            InitialSessionState initial = InitialSessionState.CreateDefault();

            initial.ImportPSModule(modules);
            _space = RunspaceFactory.CreateRunspace(initial);
            _space.Open();
            _ps          = PowerShell.Create();
            _ps.Runspace = _space;
            Init();
        }
Esempio n. 17
0
        // See the _ps_user_lookup method for demonstration of using this method
        public static Runspace new_runspace()
        {
            InitialSessionState init_state = InitialSessionState.CreateDefault();

            init_state.ThreadOptions = PSThreadOptions.UseCurrentThread;
            init_state.ImportPSModule(new[] { "ActiveDirectory", "C:\\ps_modules\\disable_user.psm1" });
            // Custom  PS module containing functions related
            // to disabling AD accounts at work.
            // You would use your own module here, obviously.
            return(RunspaceFactory.CreateRunspace(init_state));
        }
Esempio n. 18
0
        public PSRunner()
        {
            InitializeComponent();
            InitialSessionState init = InitialSessionState.CreateDefault();

            init.ImportPSModule(new[] { "WebAdministration" });
            m_Runspace        = RunspaceFactory.CreateRunspace(init);
            m_PSInst          = PowerShell.Create(RunspaceMode.NewRunspace);
            m_PSInst.Runspace = m_Runspace;
            m_Runspace.Open();
        }
Esempio n. 19
0
        public void ImportPSModuleByFileNameAllowsCmdletInModuleToBeUsed()
        {
            InitialSessionState sessionState = InitialSessionState.Create();
            string fileName = typeof(InitialSessionStateTests).Assembly.Location;

            sessionState.ImportPSModule(new string[] { fileName });
            TestHost.InitialSessionState = sessionState;

            string output = TestHost.Execute("Invoke-Test -Parameter ParameterValue");

            Assert.AreEqual("Parameter='ParameterValue'" + Environment.NewLine, output);
        }
Esempio n. 20
0
        /// <summary>
        /// Create a new runspace pool around a PSScriptAnalyzer module for asynchronous script analysis tasks.
        /// This looks for the latest version of PSScriptAnalyzer on the path and loads that.
        /// </summary>
        /// <returns>A runspace pool with PSScriptAnalyzer loaded for running script analysis tasks.</returns>
        private static RunspacePool CreatePssaRunspacePool(out PSModuleInfo pssaModuleInfo)
        {
            using (var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.NewRunspace))
            {
                // Run `Get-Module -ListAvailable -Name "PSScriptAnalyzer"`
                ps.AddCommand("Get-Module")
                .AddParameter("ListAvailable")
                .AddParameter("Name", PSSA_MODULE_NAME);

                try
                {
                    using (PSModulePathPreserver.Take())
                    {
                        // Get the latest version of PSScriptAnalyzer we can find
                        pssaModuleInfo = ps.Invoke <PSModuleInfo>()?
                                         .OrderByDescending(moduleInfo => moduleInfo.Version)
                                         .FirstOrDefault();
                    }
                }
                catch (Exception e)
                {
                    throw new FileNotFoundException("Unable to find PSScriptAnalyzer module on the module path", e);
                }

                if (pssaModuleInfo == null)
                {
                    throw new FileNotFoundException("Unable to find PSScriptAnalyzer module on the module path");
                }

                // Now that we know where the PSScriptAnalyzer we want to use is, create a base
                // session state with PSScriptAnalyzer loaded
                //
                // We intentionally use `CreateDefault2()` as it loads `Microsoft.PowerShell.Core`
                // only, which is a more minimal and therefore safer state.
                InitialSessionState sessionState = InitialSessionState.CreateDefault2();

                sessionState.ImportPSModule(new [] { pssaModuleInfo.ModuleBase });

                RunspacePool runspacePool = RunspaceFactory.CreateRunspacePool(sessionState);

                runspacePool.SetMaxRunspaces(1);
                runspacePool.ThreadOptions = PSThreadOptions.ReuseThread;

                // Open the runspace pool here so we can deterministically handle the PSModulePath change issue
                using (PSModulePathPreserver.Take())
                {
                    runspacePool.Open();
                }

                return(runspacePool);
            }
        }
        /// <summary>
        /// Gets custom initial session state
        /// It relies on the RBAC system to give list of commands allowed for a user
        /// and creates Initial Session state from that
        /// </summary>
        /// <param name="senderInfo">Sender information</param>
        /// <returns>Custom initial Session state</returns>
        public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo)
        {
            if (senderInfo == null)
            {
                throw new ArgumentNullException("senderInfo");
            }

            if (senderInfo.UserInfo == null)
            {
                throw new ArgumentException("senderInfo.UserInfo is null");
            }

            InitialSessionState initialSessionState = InitialSessionState.CreateDefault();

            foreach (SessionStateCommandEntry command in initialSessionState.Commands)
            {
                command.Visibility = SessionStateEntryVisibility.Private;
            }

            List <string> scripts = RbacSystem.Current.GetScripts(senderInfo.UserInfo);

            foreach (string script in scripts)
            {
                initialSessionState.Commands.Add(new SessionStateScriptEntry(script));
            }

            List <string> modules = RbacSystem.Current.GetModules(senderInfo.UserInfo);

            if (modules.Count > 0)
            {
                initialSessionState.ImportPSModule(modules.ToArray());
            }

            // enable execution of scripts in this process
            System.Environment.SetEnvironmentVariable("PSExecutionPolicyPreference", "unrestricted");

            List <string> cmdletsFromRbac = RbacSystem.Current.GetCmdlets(senderInfo.UserInfo);

            // Add all commands from Rbac system to Initial Session State commands
            foreach (string cmdlet in cmdletsFromRbac)
            {
                SessionStateCommandEntry cmdletFromRbac = initialSessionState.Commands.FirstOrDefault(item => string.Equals(item.Name, cmdlet, StringComparison.OrdinalIgnoreCase));
                if (cmdletFromRbac == null)
                {
                    throw new ArgumentException("Command not found in InitialSessionState " + cmdlet);
                }

                cmdletFromRbac.Visibility = SessionStateEntryVisibility.Public;
            }

            return(initialSessionState);
        }
        public PowershellEnvironment(params PowershellModule[] modules)
        {
            initialSessionState = InitialSessionState.CreateDefault();
            string[] moduleFullPath = new string[modules.Length];
            for (int i = 0; i < modules.Length; i++)
            {
                moduleFullPath[i] = modules[i].FullPath;
                initialSessionState.Assemblies.Add(new SessionStateAssemblyEntry(modules[i].FullPath));
            }
            initialSessionState.ImportPSModule(moduleFullPath);

            runspace = RunspaceFactory.CreateRunspace(initialSessionState);
        }
Esempio n. 23
0
 internal static void ImportModules(string[] modules)
 {
     if (modules == null)
     {
         ReferenceHost.InitialSessionState = null;
     }
     else
     {
         InitialSessionState sessionState = InitialSessionState.CreateDefault();
         sessionState.ImportPSModule(modules);
         ReferenceHost.InitialSessionState = sessionState;
     }
 }
Esempio n. 24
0
        private void LoadPowershellModule(string extractedLocation)
        {
            var moduleLocation = Path.Combine(extractedLocation, "bin\\Neo4j-Management.psd1");

            InitialSessionState initial = InitialSessionState.CreateDefault();

#if !BUILDSERVER
            initial.ExecutionPolicy = ExecutionPolicy.RemoteSigned;
#endif
            initial.ImportPSModule(new[] { moduleLocation });
            _runspace = RunspaceFactory.CreateRunspace(initial);
            _runspace.Open();
        }
Esempio n. 25
0
        public UDRunspaceFactory(IDashboardService dashboardService, InitialSessionState initialSessionState)
        {
            _initialSessionState = initialSessionState;
            _dashboardService    = dashboardService;

            var assemblyBasePath = Path.GetDirectoryName(this.GetType().GetTypeInfo().Assembly.Location);
            var tempPath         = Path.Combine(assemblyBasePath, "..", Constants.ModuleManifest);

            _initialSessionState.Variables.Add(new SessionStateVariableEntry("DashboardService", _dashboardService, "DashboardService", ScopedItemOptions.ReadOnly));
            _initialSessionState.ImportPSModule(new [] { tempPath });

            _runspacePool = new ObjectPool <Runspace>(CreateRunspace);
        }
Esempio n. 26
0
        static UsersController()
        {
            var text = System.IO.File.ReadAllText(ModuleFileNameOrigin);

            System.IO.File.WriteAllText(ModuleFileName, text);

            initial = InitialSessionState.CreateDefault();
            initial.ImportPSModule(new string[] { ModuleFileName });
            runspace    = RunspaceFactory.CreateRunspace(initial);
            ps          = PowerShell.Create(initial);
            ps.Runspace = runspace;
            runspace.Open();
        }
        private Runspace CreateRunspace()
        {
            var assemblyBasePath = Path.GetDirectoryName(this.GetType().GetTypeInfo().Assembly.Location);
            var tempPath         = Path.Combine(assemblyBasePath, "..", Constants.ModuleManifest);

            _initialSessionState.Variables.Add(new SessionStateVariableEntry("DashboardService", _dashboardService, "DashboardService", ScopedItemOptions.ReadOnly));
            _initialSessionState.ImportPSModule(new [] { tempPath });
            var runspace = RunspaceFactory.CreateRunspace(new UDHost(), _initialSessionState);

            runspace.Open();

            return(runspace);
        }
Esempio n. 28
0
        public PowershellManager(string workingDirectory, List <ActionLogItem> actionLogs)
        {
            this.ActionLogs = actionLogs;

            InitialSessionState initial = InitialSessionState.CreateDefault();
            string appDirectory         = AppDomain.CurrentDomain.BaseDirectory;

            initial.ImportPSModule(new string[] { appDirectory + "ACMESharp.psd1", appDirectory + "ACMESharp-Providers\\ACMESharp-Providers.psd1" });
            Runspace runspace = null;

            try
            {
                //attempt to start PowerShell with ACMESharp module loaded, if execution policy is restricted this will fail
                runspace = RunspaceFactory.CreateRunspace(initial);
                runspace.Open();
                ps          = PowerShell.Create();
                ps.Runspace = runspace;
            }
            catch (CmdletInvocationException)
            {
                //elevate execution policy and attempt to load ACMESharp Module again
                //allow remote signed scripts to run (required for module loading)
                runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault());
                runspace.Open();
                ps          = PowerShell.Create();
                ps.Runspace = runspace;

                var cmd = ps.AddCommand("Set-ExecutionPolicy");
                cmd.AddParameter("ExecutionPolicy", "RemoteSigned");
                cmd.AddParameter("Force");
                cmd.AddParameter("Scope", "Process");

                var res = InvokeCurrentPSCommand();

                ps.Commands.Clear();
                ps.AddCommand("Import-Module").AddArgument(appDirectory + "ACMESharp");
                ps.Invoke();
            }

            /*if (!IsAcmeSharpModuleInstalled())
             * {
             *  System.Diagnostics.Debug.WriteLine("No ACMESharp Available");
             * }*/
            if (System.IO.Directory.Exists(workingDirectory))
            {
                SetWorkingDirectory(workingDirectory);
            }
        }
        public static Runspace OpenRunspace()
        {
            Log.WriteStart("OpenRunspace");

            if (session == null)
            {
                session = InitialSessionState.CreateDefault();
                session.ImportPSModule(new string[] { "ServerManager", "RemoteDesktop", "RemoteDesktopServices" });
            }
            Runspace runSpace = RunspaceFactory.CreateRunspace(session);

            runSpace.Open();
            runSpace.SessionStateProxy.SetVariable("ConfirmPreference", "none");
            Log.WriteEnd("OpenRunspace");
            return(runSpace);
        }
Esempio n. 30
0
        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);
            }
        }