/// <summary> /// Creates a local runspace with the autoloading turned on. /// </summary> /// <returns></returns> internal static Runspace CreateLocalActivityRunspace(PSLanguageMode?languageMode = null, bool useCurrentThreadForExecution = true) { InitialSessionState iss = GetInitialSessionStateWithSharedTypesAndNoFormat(); if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { iss.LanguageMode = PSLanguageMode.ConstrainedLanguage; } if (languageMode != null && languageMode.HasValue) { iss.LanguageMode = languageMode.Value; } // Add a variable indicating that we're in Workflow endpoint. This enables the // autoloading feature. SessionStateVariableEntry ssve = new SessionStateVariableEntry("RunningInPSWorkflowEndpoint", true, "True if we're in a Workflow Endpoint", ScopedItemOptions.Constant); iss.Variables.Add(ssve); Runspace runspace = RunspaceFactory.CreateRunspace(iss); if (useCurrentThreadForExecution) { runspace.ThreadOptions = PSThreadOptions.UseCurrentThread; } return(runspace); }
public void CreatePowerShells(PowerShell power, SessionStateVariableEntry session) { sessionStates.Add(InitialSessionState.CreateDefault()); foreach (InitialSessionState s in sessionStates) { runspaces.Add(RunspaceFactory.CreateRunspace(iss)); } pslist.Add(power); if (rs != null) { foreach (Runspace r in runspaces) { foreach (PowerShell p in pslist) { p.Runspace = r; } } } foreach (Runspace r in runspaces) { r.Open(); } }
public void AddVariableToSessionState() { InitialSessionState sessionState = InitialSessionState.CreateDefault(); var variableEntry = new SessionStateVariableEntry("TestVariable", new object(), "description"); sessionState.Variables.Add(variableEntry); Assert.IsTrue(sessionState.Variables.Contains(variableEntry)); }
public static void Initialize(Action <String> writeLine = null) { WriteLine = writeLine; InitialSessionState state = InitialSessionState.CreateDefault(); SessionStateVariableEntry agentEntry = new SessionStateVariableEntry("Agent", typeof(Agent), "The Agent"); state.Variables.Add(agentEntry); powershell = PowerShell.Create(state); WriteLine("PowerShell Agent Initialized"); }
InitialSessionState CreateInitialSessionState() { var initialSessionState = InitialSessionState.CreateDefault(); initialSessionState.ImportPSModule(modulesToImport.ToArray()); SessionStateVariableEntry variable = CreateDTESessionVariable(); initialSessionState.Variables.Add(variable); return(initialSessionState); }
private void Form1_Load(object sender, EventArgs e) { WriteText("Text Box Initialized"); AppState.Mine = "YO"; var me = new AppState(); InitialSessionState state = InitialSessionState.CreateDefault(); SessionStateVariableEntry Entry1 = new SessionStateVariableEntry("MyVar", me, "description"); state.Variables.Add(Entry1); powershell = PowerShell.Create(state); }
internal static void InitExchangePropertyContainer(InitialSessionState initialSessionState, ExchangeRunspaceConfiguration configuration) { ExchangePropertyContainer exchangePropertyContainer = new ExchangePropertyContainer(); exchangePropertyContainer.logEntries = new CmdletLogEntries(); exchangePropertyContainer.exchangeRunspaceConfiguration = configuration; exchangePropertyContainer.budget = ExchangePropertyContainer.AcquirePowerShellBudget(configuration); SessionStateVariableEntry item = new SessionStateVariableEntry(ExchangePropertyContainer.ExchangePropertyContainerName, exchangePropertyContainer, ExchangePropertyContainer.ExchangePropertyContainerName, ScopedItemOptions.ReadOnly | ScopedItemOptions.Constant | ScopedItemOptions.Private | ScopedItemOptions.AllScope); initialSessionState.Variables.Add(item); }
public void NewVariableEntryWithNameValueAndDescriptionShouldHaveOptionsOfNoneAndPublicVisibility() { var value = new Object(); var entry = new SessionStateVariableEntry("name", value, "description"); Assert.AreEqual(ScopedItemOptions.None, entry.Options); Assert.AreEqual(SessionStateEntryVisibility.Public, entry.Visibility); Assert.AreEqual("description", entry.Description); Assert.AreEqual(value, entry.Value); Assert.AreEqual(0, entry.Attributes.Count); }
InitialSessionState CreateInitialSessionState() { var initialSessionState = InitialSessionState.CreateDefault(); string[] modulesToImport = PowerShellModules.GetModules().ToArray(); initialSessionState.ImportPSModule(modulesToImport); SessionStateVariableEntry variable = CreateDTESessionVariable(); initialSessionState.Variables.Add(variable); return(initialSessionState); }
Runspace GetWPFCurrentThreadRunspace(InitialSessionState sessionState) { InitialSessionState clone = sessionState.Clone(); clone.ThreadOptions = PSThreadOptions.UseCurrentThread; SessionStateVariableEntry window = new SessionStateVariableEntry("Window", JobWindow, ""); SessionStateVariableEntry namedControls = new SessionStateVariableEntry("NamedControls", this.namedControls, ""); clone.Variables.Add(window); clone.Variables.Add(namedControls); return(RunspaceFactory.CreateRunspace(clone)); }
public void VariableDefinedInInitialSessionStateCanBeUsedInStatement() { string variableValue = "testVariableValue"; var variableEntry = new SessionStateVariableEntry("testVariable", variableValue, "description"); InitialSessionState sessionState = InitialSessionState.Create(); sessionState.Variables.Add(variableEntry); TestHost.InitialSessionState = sessionState; string output = TestHost.Execute("$testVariable"); Assert.AreEqual(variableValue + Environment.NewLine, output); }
public void NewVariableEntryCreatedWithSingleAttributeShouldHaveSingleAttribute() { var value = new Object(); var attribute = new CredentialAttribute(); var entry = new SessionStateVariableEntry("name", value, "description", ScopedItemOptions.Constant, attribute); Assert.AreEqual(1, entry.Attributes.Count); Assert.AreEqual(attribute, entry.Attributes[0]); Assert.AreEqual(value, entry.Value); Assert.AreEqual("name", entry.Name); Assert.AreEqual("description", entry.Description); Assert.AreEqual(ScopedItemOptions.Constant, entry.Options); }
public void NewVariableEntryCreatedWithTwoAttributesShouldHaveSingleAttributes() { var value = new Object(); var attributes = new Collection <Attribute>(); attributes.Add(new CredentialAttribute()); attributes.Add(new CredentialAttribute()); var entry = new SessionStateVariableEntry("name", value, "description", ScopedItemOptions.Constant, attributes); CollectionAssert.AreEqual(attributes, entry.Attributes); Assert.AreEqual(value, entry.Value); Assert.AreEqual("name", entry.Name); Assert.AreEqual("description", entry.Description); Assert.AreEqual(ScopedItemOptions.Constant, entry.Options); }
public bool CreatePsPipeline() { _startTime = DateTime.MinValue; _endTime = DateTime.MinValue; _taskCompleted = false; _taskStatus = Status.NOTSTARTED; _resultDataTable = null; _resultStringBuilder = new StringBuilder(); try { InitialSessionState iss = InitialSessionState.CreateDefault(); foreach (var v in _variables) { SessionStateVariableEntry variable = new SessionStateVariableEntry(v.Key, v.Value, null); iss.Variables.Add(variable); } _runspace = RunspaceFactory.CreateRunspace(initialSessionState: iss); } catch { _taskCompleted = true; _taskStatus = Status.FAILED; throw; } try { _runspace.Open(); _pipeline = _runspace.CreatePipeline(); foreach (var scriptFile in _scriptFiles) { string scriptContent = System.IO.File.ReadAllText(scriptFile); _pipeline.Commands.AddScript(scriptContent); } _pipeline.Commands.AddScript(_scriptText); } catch { _taskStatus = Status.FAILED; throw; } return(true); }
internal static Runspace CreateLocalActivityRunspace(PSLanguageMode?languageMode = null, bool useCurrentThreadForExecution = true) { InitialSessionState initialSessionStateWithSharedTypesAndNoFormat = LocalRunspaceProvider.GetInitialSessionStateWithSharedTypesAndNoFormat(); if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) { initialSessionStateWithSharedTypesAndNoFormat.LanguageMode = PSLanguageMode.ConstrainedLanguage; } if (languageMode.HasValue && languageMode.HasValue) { initialSessionStateWithSharedTypesAndNoFormat.LanguageMode = languageMode.Value; } SessionStateVariableEntry sessionStateVariableEntry = new SessionStateVariableEntry("RunningInPSWorkflowEndpoint", (object)((bool)1), "True if we're in a Workflow Endpoint", ScopedItemOptions.Constant); initialSessionStateWithSharedTypesAndNoFormat.Variables.Add(sessionStateVariableEntry); Runspace runspace = RunspaceFactory.CreateRunspace(initialSessionStateWithSharedTypesAndNoFormat); if (useCurrentThreadForExecution) { runspace.ThreadOptions = PSThreadOptions.UseCurrentThread; } return(runspace); }
public void Add(SessionStateVariableEntry session) { sSVarEntries.Add(session); iss.Variables.Add(sSVarEntries); }
private static List <string> GetSingleAstRequiredModules(Ast ast, Token[] tokens) { List <string> modules = new List <string>(); List <string> resources = new List <string>(); var imports = tokens.Where(token => String.Compare(token.Text, "Import-DscResource", StringComparison.OrdinalIgnoreCase) == 0); // // Create a function with the same name as Import-DscResource keyword and use powershell // argument function binding to emulate Import-DscResource argument binding. // InitialSessionState initialSessionState = InitialSessionState.Create(); SessionStateFunctionEntry importDscResourcefunctionEntry = new SessionStateFunctionEntry( "Import-DscResource", @"param($Name, $ModuleName) if ($ModuleName) { foreach ($m in $ModuleName) { $global:modules.Add($m) } } else { foreach ($n in $Name) { $global:resources.Add($n) } } "); initialSessionState.Commands.Add(importDscResourcefunctionEntry); initialSessionState.LanguageMode = PSLanguageMode.RestrictedLanguage; var moduleVarEntry = new SessionStateVariableEntry("modules", modules, ""); var resourcesVarEntry = new SessionStateVariableEntry("resources", resources, ""); initialSessionState.Variables.Add(moduleVarEntry); initialSessionState.Variables.Add(resourcesVarEntry); using (System.Management.Automation.PowerShell powerShell = System.Management.Automation.PowerShell.Create(initialSessionState)) { foreach (var import in imports) { int startOffset = import.Extent.StartOffset; var asts = ast.FindAll(a => IsCandidateForImportDscResourceAst(a, startOffset), true); int longestLen = -1; Ast longestCandidate = null; foreach (var candidatAst in asts) { int curLen = candidatAst.Extent.EndOffset - candidatAst.Extent.StartOffset; if (curLen > longestLen) { longestCandidate = candidatAst; longestLen = curLen; } } // longestCandidate should contain AST for import-dscresource, like "Import-DSCResource -Module x -Name y". if (longestCandidate != null) { string importText = longestCandidate.Extent.Text; // We invoke-command "importText" here. Script injection is prevented: // We checked that file represents a valid AST without errors. powerShell.AddScript(importText); powerShell.Invoke(); powerShell.Commands.Clear(); } } } modules.AddRange(resources.Select(GetModuleNameForDscResource)); return(modules); }
static void PowershellThread(object state) { var cliArgs = (PsEntrypointArgs)state; if (!string.IsNullOrWhiteSpace(cliArgs.EntrypointScript)) { cliArgs.EntrypointCommand = System.IO.File.ReadAllText(cliArgs.EntrypointScript); } if (!string.IsNullOrWhiteSpace(cliArgs.ShutdownScript)) { cliArgs.ShutdownCommand = System.IO.File.ReadAllText(cliArgs.ShutdownScript); } var initialSessionState = InitialSessionState.CreateDefault(); var entrypointVariable = new SessionStateVariableEntry(EntrypointVariableName, (IEntrypointState)EntrypointState, EntrypointVariableDescription, ScopedItemOptions.AllScope | ScopedItemOptions.ReadOnly); initialSessionState.Variables.Add(entrypointVariable); var psHost = new PsEntrypointPSHost(); using (var runspace = RunspaceFactory.CreateRunspace(psHost, initialSessionState)) { PowerShell powershell; runspace.Open(); // run entrypoint command using (powershell = PowerShell.Create()) { powershell.Runspace = runspace; powershell.AddCommand("Set-ExecutionPolicy").AddParameter("-ExecutionPolicy", "Bypass").AddParameter("-Scope", "Process").Invoke(); if (!string.IsNullOrWhiteSpace(cliArgs.EntrypointScript)) { var entrypointScript = runspace.SessionStateProxy.InvokeCommand.GetCommand(cliArgs.EntrypointScript, CommandTypes.ExternalScript); powershell.AddCommand(entrypointScript); } else { powershell.AddScript(cliArgs.EntrypointCommand); } var entrypointResult = powershell.BeginInvoke(); logger.WriteLog("Entrypoint started"); Thread.Sleep(5); try { foreach (var result in powershell.EndInvoke(entrypointResult)) { Console.WriteLine(result.ToString()); } } catch (ThreadInterruptedException) { logger.WriteLog("Entrypoint interrupted. Terminating..."); powershell.Stop(); } catch (Exception problem) { logger.WriteLog($"Entrypoint crashed: {problem}"); } finally { logger.WriteLog("Entrypoint stopped"); } } // signal entrypoint terminated entrypointTerminated.Set(); // run shutdown command if (!string.IsNullOrWhiteSpace(cliArgs.ShutdownCommand)) { using (powershell = PowerShell.Create()) { powershell.Runspace = runspace; if (!string.IsNullOrWhiteSpace(cliArgs.ShutdownScript)) { var shutdownScript = runspace.SessionStateProxy.InvokeCommand.GetCommand(cliArgs.ShutdownScript, CommandTypes.ExternalScript); powershell.AddCommand(shutdownScript); } else { powershell.AddScript(cliArgs.ShutdownCommand); } var shutdownResult = powershell.BeginInvoke(); Console.WriteLine("Shutdown initiated"); Thread.Sleep(5); try { foreach (var result in powershell.EndInvoke(shutdownResult)) { Console.WriteLine(result.ToString()); } logger.WriteLog("Shutdown completed"); } catch (ThreadInterruptedException) { logger.WriteLog("Shutdown interrupted. Terminating..."); powershell.Stop(); } catch (Exception problem) { logger.WriteLog($"Shutdown crashed: {problem}"); } finally { logger.WriteLog("Shutdown ended"); } } } runspace.Close(); } shutdownTerminated.Set(); }
public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo) { InitialSessionState state = null; bool flag = false; string str = TryGetValue(this.configHash, ConfigFileContants.SessionType); SessionType type = SessionType.Default; bool flag2 = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleCmdlets); bool flag3 = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleFunctions); bool flag4 = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleAliases); bool flag5 = this.IsNonDefaultVisibiltySpecified(ConfigFileContants.VisibleProviders); if (!string.IsNullOrEmpty(str)) { type = (SessionType)Enum.Parse(typeof(SessionType), str, true); switch (type) { case SessionType.Empty: state = InitialSessionState.Create(); goto Label_00AD; case SessionType.RestrictedRemoteServer: state = InitialSessionState.CreateRestricted(SessionCapabilities.RemoteServer); if (flag5) { InitialSessionState state2 = InitialSessionState.CreateDefault2(); state.Providers.Add(state2.Providers); } goto Label_00AD; } state = InitialSessionState.CreateDefault2(); } else { state = InitialSessionState.CreateDefault2(); } Label_00AD: if (this.configHash.ContainsKey(ConfigFileContants.AssembliesToLoad)) { string[] strArray = TryGetStringArray(this.configHash[ConfigFileContants.AssembliesToLoad]); if (strArray != null) { foreach (string str2 in strArray) { state.Assemblies.Add(new SessionStateAssemblyEntry(str2)); } } } if (this.configHash.ContainsKey(ConfigFileContants.ModulesToImport)) { object[] objArray = TryGetObjectsOfType <object>(this.configHash[ConfigFileContants.ModulesToImport], new Type[] { typeof(string), typeof(Hashtable) }); if ((this.configHash[ConfigFileContants.ModulesToImport] != null) && (objArray == null)) { PSInvalidOperationException exception = new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.DISCTypeMustBeStringOrHashtableArray, ConfigFileContants.ModulesToImport)); exception.SetErrorId("InvalidModulesToImportKeyEntries"); throw exception; } if (objArray != null) { Collection <ModuleSpecification> modules = new Collection <ModuleSpecification>(); foreach (object obj2 in objArray) { ModuleSpecification item = null; string str4 = obj2 as string; if (!string.IsNullOrEmpty(str4)) { item = new ModuleSpecification(str4); } else { Hashtable moduleSpecification = obj2 as Hashtable; if (moduleSpecification != null) { item = new ModuleSpecification(moduleSpecification); } } if (item != null) { if (string.Equals(InitialSessionState.CoreModule, item.Name, StringComparison.OrdinalIgnoreCase)) { if (type == SessionType.Empty) { state.ImportCorePSSnapIn(); } } else { modules.Add(item); } } } state.ImportPSModule(modules); } } if (this.configHash.ContainsKey(ConfigFileContants.AliasDefinitions)) { Hashtable[] hashtableArray = TryGetHashtableArray(this.configHash[ConfigFileContants.AliasDefinitions]); if (hashtableArray != null) { foreach (Hashtable hashtable2 in hashtableArray) { SessionStateAliasEntry entry = this.CreateSessionStateAliasEntry(hashtable2); if (entry != null) { state.Commands.Add(entry); } } } } if (this.configHash.ContainsKey(ConfigFileContants.FunctionDefinitions)) { Hashtable[] hashtableArray2 = TryGetHashtableArray(this.configHash[ConfigFileContants.FunctionDefinitions]); if (hashtableArray2 != null) { foreach (Hashtable hashtable3 in hashtableArray2) { SessionStateFunctionEntry entry2 = this.CreateSessionStateFunctionEntry(hashtable3); if (entry2 != null) { state.Commands.Add(entry2); } } } } if (this.configHash.ContainsKey(ConfigFileContants.VariableDefinitions)) { Hashtable[] hashtableArray3 = TryGetHashtableArray(this.configHash[ConfigFileContants.VariableDefinitions]); if (hashtableArray3 != null) { foreach (Hashtable hashtable4 in hashtableArray3) { if (!hashtable4.ContainsKey(ConfigFileContants.VariableValueToken) || !(hashtable4[ConfigFileContants.VariableValueToken] is ScriptBlock)) { SessionStateVariableEntry entry3 = this.CreateSessionStateVariableEntry(hashtable4); if (entry3 != null) { state.Variables.Add(entry3); } } } } } if (this.configHash.ContainsKey(ConfigFileContants.TypesToProcess)) { string[] strArray2 = TryGetStringArray(this.configHash[ConfigFileContants.TypesToProcess]); if (strArray2 != null) { foreach (string str5 in strArray2) { if (!string.IsNullOrEmpty(str5)) { state.Types.Add(new SessionStateTypeEntry(str5)); } } } } if (this.configHash.ContainsKey(ConfigFileContants.FormatsToProcess)) { string[] strArray3 = TryGetStringArray(this.configHash[ConfigFileContants.FormatsToProcess]); if (strArray3 != null) { foreach (string str6 in strArray3) { if (!string.IsNullOrEmpty(str6)) { state.Formats.Add(new SessionStateFormatEntry(str6)); } } } } if ((flag2 || flag3) || (flag4 || flag5)) { flag = true; } if (flag) { state.Variables.Add(new SessionStateVariableEntry("PSModuleAutoLoadingPreference", PSModuleAutoLoadingPreference.None, string.Empty, ScopedItemOptions.None)); if (type == SessionType.Default) { state.ImportPSCoreModule(InitialSessionState.EngineModules.ToArray <string>()); } if (!flag2) { state.Commands.Remove("Import-Module", typeof(SessionStateCmdletEntry)); } if (!flag4) { state.Commands.Remove("ipmo", typeof(SessionStateAliasEntry)); } } return(state); }