public object Invoke(ScriptBlock sb, params object[] args) { object obj2; if (sb == null) { return(null); } SessionStateInternal sessionStateInternal = sb.SessionStateInternal; try { sb.SessionStateInternal = this._sessionState.Internal; obj2 = sb.InvokeReturnAsIs(args); } finally { sb.SessionStateInternal = sessionStateInternal; } return(obj2); }
/// <summary> /// Get a Hashtable object out of a PowerShell data file (.psd1) /// </summary> /// <param name="parameterName"> /// Name of the parameter that takes the specified .psd1 file as a value /// </param> /// <param name="psDataFilePath"> /// Path to the powershell data file /// </param> /// <param name="context"> /// ExecutionContext to use /// </param> /// <param name="allowedCommands"> /// Set of command names that are allowed to use in the .psd1 file /// </param> /// <param name="allowedVariables"> /// Set of variable names that are allowed to use in the .psd1 file /// </param> /// <param name="allowEnvironmentVariables"> /// If true, allow to use environment variables in the .psd1 file /// </param> /// <param name="skipPathValidation"> /// If true, caller guarantees the path is valid /// </param> /// <returns></returns> internal static Hashtable EvaluatePowerShellDataFile( string parameterName, string psDataFilePath, ExecutionContext context, IEnumerable <string> allowedCommands, IEnumerable <string> allowedVariables, bool allowEnvironmentVariables, bool skipPathValidation) { if (!skipPathValidation && string.IsNullOrEmpty(parameterName)) { throw PSTraceSource.NewArgumentNullException("parameterName"); } if (string.IsNullOrEmpty(psDataFilePath)) { throw PSTraceSource.NewArgumentNullException("psDataFilePath"); } if (context == null) { throw PSTraceSource.NewArgumentNullException("context"); } string resolvedPath; if (skipPathValidation) { resolvedPath = psDataFilePath; } else { #region "ValidatePowerShellDataFilePath" bool isPathValid = true; // File extension needs to be .psd1 string pathExt = Path.GetExtension(psDataFilePath); if (string.IsNullOrEmpty(pathExt) || !StringLiterals.PowerShellDataFileExtension.Equals(pathExt, StringComparison.OrdinalIgnoreCase)) { isPathValid = false; } ProviderInfo provider; var resolvedPaths = context.SessionState.Path.GetResolvedProviderPathFromPSPath(psDataFilePath, out provider); // ConfigPath should be resolved as FileSystem provider if (provider == null || !Microsoft.PowerShell.Commands.FileSystemProvider.ProviderName.Equals(provider.Name, StringComparison.OrdinalIgnoreCase)) { isPathValid = false; } // ConfigPath should be resolved to a single path if (resolvedPaths.Count != 1) { isPathValid = false; } if (!isPathValid) { throw PSTraceSource.NewArgumentException( parameterName, ParserStrings.CannotResolvePowerShellDataFilePath, psDataFilePath); } resolvedPath = resolvedPaths[0]; #endregion "ValidatePowerShellDataFilePath" } #region "LoadAndEvaluatePowerShellDataFile" object evaluationResult; try { // Create the scriptInfo for the .psd1 file string dataFileName = Path.GetFileName(resolvedPath); var dataFileScriptInfo = new ExternalScriptInfo(dataFileName, resolvedPath, context); ScriptBlock scriptBlock = dataFileScriptInfo.ScriptBlock; // Validate the scriptblock scriptBlock.CheckRestrictedLanguage(allowedCommands, allowedVariables, allowEnvironmentVariables); // Evaluate the scriptblock object oldPsScriptRoot = context.GetVariableValue(SpecialVariables.PSScriptRootVarPath); try { // Set the $PSScriptRoot before the evaluation context.SetVariable(SpecialVariables.PSScriptRootVarPath, Path.GetDirectoryName(resolvedPath)); evaluationResult = PSObject.Base(scriptBlock.InvokeReturnAsIs()); } finally { context.SetVariable(SpecialVariables.PSScriptRootVarPath, oldPsScriptRoot); } } catch (RuntimeException ex) { throw PSTraceSource.NewInvalidOperationException( ex, ParserStrings.CannotLoadPowerShellDataFile, psDataFilePath, ex.Message); } var retResult = evaluationResult as Hashtable; if (retResult == null) { throw PSTraceSource.NewInvalidOperationException( ParserStrings.InvalidPowerShellDataFile, psDataFilePath); } #endregion "LoadAndEvaluatePowerShellDataFile" return(retResult); }
public object Invoke(ScriptBlock sb, params object[] args) { object obj2; if (sb == null) { return null; } SessionStateInternal sessionStateInternal = sb.SessionStateInternal; try { sb.SessionStateInternal = this._sessionState.Internal; obj2 = sb.InvokeReturnAsIs(args); } finally { sb.SessionStateInternal = sessionStateInternal; } return obj2; }
private void runSBEvent(ScriptBlock sb, AutomationElement src, AutomationEventArgs e) { // inform the Wait-UIAEventRaised cmdlet SaveEventInput( src, e, e.EventId.ProgrammaticName, true); // try { // CurrentData.LastEventSource = src; // as AutomationElement; // CurrentData.LastEventArgs = e; // as AutomationEventArgs; // CurrentData.LastEventType = e.EventId.ProgrammaticName; // CurrentData.LastEventInfoAdded = true; // } // catch { // //WriteVerbose(this, "failed to register an event in the collection"); // } // 20120206 Collection<PSObject > psObjects = null; try { System.Management.Automation.Runspaces.Runspace.DefaultRunspace = RunspaceFactory.CreateRunspace(); try { System.Management.Automation.Runspaces.Runspace.DefaultRunspace.Open(); } catch (Exception e1) { // 20130318 // ErrorRecord err = // new ErrorRecord(e1, // "ErrorOnOpeningRunspace", // ErrorCategory.InvalidOperation, // sb); // err.ErrorDetails = // new ErrorDetails( // "Unable to run a scriptblock:\r\n" + // sb.ToString()); // WriteError(this, err, false); this.WriteError( this, "Unable to run a scriptblock:\r\n" + sb.ToString() + "." + e1.Message, "ErrorOnOpeningRunspace", ErrorCategory.InvalidOperation, // 20130318 //false); true); } try { System.Collections.Generic.List<object> inputParams = new System.Collections.Generic.List<object>(); inputParams.Add(src); inputParams.Add(e); object[] inputParamsArray = inputParams.ToArray(); // psObjects = sb.InvokeReturnAsIs(inputParamsArray); // sb.Invoke(inputParamsArray); } catch (Exception e2) { // 20130318 // ErrorRecord err = // new ErrorRecord(e2, // "ErrorInOpenedRunspace", // ErrorCategory.InvalidOperation, // sb); // err.ErrorDetails = // new ErrorDetails("Unable to run a scriptblock"); // WriteError(this, err, true); this.WriteError( this, "Unable to run a scriptblock." + e2.Message, "ErrorInOpenedRunspace", ErrorCategory.InvalidOperation, true); } // psObjects = // sb.Invoke(); } catch (Exception eOuter) { // 20130318 // ErrorRecord err = // new ErrorRecord(eOuter, // "ErrorInInvokingScriptBlock", //"ErrorinCreatingRunspace", // ErrorCategory.InvalidOperation, // System.Management.Automation.Runspaces.Runspace.DefaultRunspace); // err.ErrorDetails = // new ErrorDetails("Unable to issue the following command:\r\n" + // "System.Management.Automation.Runspaces.Runspace.DefaultRunspace = RunspaceFactory.CreateRunspace();" + // "\r\nException raised is\r\n" + // eOuter.Message); this.WriteError( this, "Unable to issue the following command:\r\n" + "System.Management.Automation.Runspaces.Runspace.DefaultRunspace = RunspaceFactory.CreateRunspace();" + "\r\nException raised is\r\n" + eOuter.Message, "ErrorInInvokingScriptBlock", ErrorCategory.InvalidOperation, true); } }
/// <summary> /// Invokes the handler-like script and returns the result as it is. /// </summary> /// <param name="script">The script block to invoke.</param> /// <param name="args">Script arguments.</param> internal static object InvokeScriptReturnAsIs(ScriptBlock script, params object[] args) { if (Runspace.DefaultRunspace == null) Runspace.DefaultRunspace = Psf.Runspace; return script.InvokeReturnAsIs(args); }