protected override void EndProcessing() { var closure = ClosureRewriter.CreateNewClosure(ScriptBlock, DelegateType); var sbAst = ScriptBlock.Ast as ScriptBlockAst; var e = sbAst.Extent; var invokeDelegateExpr = new InvokeMemberExpressionAst( e, new ConstantExpressionAst(e, closure), new StringConstantExpressionAst(e, nameof(Action.Invoke), StringConstantType.BareWord), Array.Empty <ExpressionAst>(), @static: false); var invokeDelegateStmt = new CommandExpressionAst( e, invokeDelegateExpr, Array.Empty <RedirectionAst>()); var newSbAst = new ScriptBlockAst( e, sbAst.UsingStatements, Array.Empty <AttributeAst>(), null, null, null, new NamedBlockAst( e, TokenKind.End, new StatementBlockAst(e, new[] { invokeDelegateStmt }, Array.Empty <TrapStatementAst>()), unnamed: true), null); WriteObject(newSbAst.GetScriptBlock()); }
private ScriptBlock GetScriptBlockFromFile(string filePath, PSCmdlet psCmdlet) { if (WildcardPattern.ContainsWildcardCharacters(filePath)) { throw new ArgumentException(Properties.Resources.ResourceManager.GetString("FilePathWildcards")); } if (!filePath.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(Properties.Resources.ResourceManager.GetString("FilePathExt")); } ProviderInfo provider = null; string resolvedPath = psCmdlet.GetResolvedProviderPathFromPSPath(filePath, out provider).FirstOrDefault(); if (!string.IsNullOrEmpty(resolvedPath)) { Token[] tokens; ParseError[] errors; ScriptBlockAst scriptBlockAst = Parser.ParseFile(resolvedPath, out tokens, out errors); if (scriptBlockAst != null && errors.Length == 0) { return(scriptBlockAst.GetScriptBlock()); } foreach (var error in errors) { this.Error.Add( new ErrorRecord( new ParseException(error.Message), "ThreadJobError", ErrorCategory.InvalidData, this)); } } return(null); }
/// <summary> /// Method to read the provided script file and either write /// the created instrumented AST object or write elapsed time /// for each line in script. /// </summary> /// <param name="file"></param> private void Profile(string file) { Token[] tokens; ParseError[] errors; var ast = Parser.ParseFile(file, out tokens, out errors); Profiler profiler = new Profiler(ast.Extent); var instrumentor = new InstrumentAst { Profiler = profiler }; ScriptBlockAst newAst = (ScriptBlockAst)ast.Visit(instrumentor); if (Ast) { WriteObject(newAst); return; } ScriptBlock sb = newAst.GetScriptBlock(); sb.Invoke(); string[] allLines = File.ReadAllLines(file); for (int i = 0; i < allLines.Length; ++i) { long time = (i >= profiler.StopWatches.Length) ? 0 : profiler.StopWatches[i].ElapsedMilliseconds; var result = new PSObject(); result.Members.Add(new PSNoteProperty("Time", time)); result.Members.Add(new PSNoteProperty("Line", allLines[i])); WriteObject(result); } }
/// <summary> /// Initializes a new <see cref="TestScript"/>. /// </summary> /// <param name="scriptSyntaxTree">The syntax tree for a script</param> /// <param name="tests">The tests belonging to the script</param> /// <param name="testSetup">An optional test setup function</param> /// <param name="testCleanup">An optional test cleanup function</param> public TestScript(ScriptBlockAst scriptSyntaxTree, IEnumerable <TestFunction> tests, Option <FunctionDefinitionAst> testSetup, Option <FunctionDefinitionAst> testCleanup) { if (scriptSyntaxTree == null) { throw new ArgumentNullException("scriptSyntaxTree"); } if (tests == null) { throw new ArgumentNullException("tests"); } if (testSetup == null) { throw new ArgumentNullException("testSetup"); } if (testCleanup == null) { throw new ArgumentNullException("testCleanup"); } _scriptSyntaxTree = scriptSyntaxTree; Source = new FileInfo(_scriptSyntaxTree.Extent.File); ScriptBlock = _scriptSyntaxTree.GetScriptBlock(); _tests = new List <TestFunction>(tests); TestSetup = testSetup; TestCleanup = testCleanup; }
protected override void ProcessRecord() { base.ProcessRecord(); ScriptBlock sb = ScriptBlock; if (null == sb) { // We must be using a "file" param set. ScriptBlockAst ast = LoadScript(File); sb = ast.GetScriptBlock(); } if (ParameterSetName.Contains("UseNewChildScope")) { WriteObject(InvokeScript(InvokeCommand, sb, UseNewChildScope), true); } else if (ParameterSetName.Contains("SessionState")) { WriteObject(this.InvokeCommand.InvokeScript(SessionStateScope, sb, null), true); } else { Util.Assert(ParameterSetName.Contains("Context")); WriteObject(InvokeWithContext(sb, WithContext, SaveContext), true); } } // end ProcessRecord()
public IEnumerator <DSResource> InvokeAsync(Expression expression, bool noStreamingResponse) { IEnumerator <DSResource> enumerator; using (OperationTracer operationTracer = new OperationTracer("Entering Pipeline.InvokeAsync")) { MonitorLock monitorLock = new MonitorLock(this); MonitorLock monitorLock1 = monitorLock; using (monitorLock) { if (this.Command == null || this.OutputFormat == null) { throw new DataServiceException(ExceptionHelpers.GetExceptionMessage(Resources.InvalidInvocationData, new object[0])); } else { this.ExpirationTime = DateTimeHelper.UtcNow; DateTime expirationTime = this.ExpirationTime; this.ExpirationTime = expirationTime.AddMilliseconds((double)this.WaitMsec); DateTime dateTime = this.ExpirationTime; this.ExpirationTime = dateTime.AddSeconds((double)DataServiceController.Current.Configuration.Invocation.Lifetime); WindowsImpersonationContext windowsImpersonationContext = this.executionToken.Instance.Impersonate(); using (windowsImpersonationContext) { using (OperationTracer operationTracer1 = new OperationTracer("PowerShell.Create")) { ScriptBlockAst scriptBlockAst = this.ValidateAndBuildPipeline(string.Concat(this.Command, "| ConvertTo-", this.OutputFormat)); Runspace.DefaultRunspace = this.runspace.Item.Runspace; this.powerShell = scriptBlockAst.GetScriptBlock().GetPowerShell(new object[0]); this.powerShell.Runspace = this.runspace.Item.Runspace; Runspace.DefaultRunspace = null; } TraceHelper.Current.BeginOperation0("RunspaceContext.Create"); DefaultRunspaceContext defaultRunspaceContext = DefaultRunspaceContext.Create(this.runspace.Item.Runspace); using (defaultRunspaceContext) { TraceHelper.Current.EndOperation("RunspaceContext.Create"); TraceHelper.Current.PipelineStart(this.ID, this.Command, this.OutputFormat); this.outputObjects.DataAdded += new EventHandler <DataAddedEventArgs>(this.DataAddedEventHandler); this.powerShell.BeginInvoke <PSObject, PSObject>(null, this.outputObjects, Utils.GetPSInvocationSettings(), this.TestHookCompletionCallback, null); monitorLock1.Exit(); this.finished.WaitOne(this.WaitMsec); this.timer.Start(); monitorLock1.Enter(); List <DSResource> dSResources = new List <DSResource>(); dSResources.Add(this.MakeDsResource()); TraceHelper.Current.DebugMessage("Exiting Pipeline.InvokeAsync"); enumerator = dSResources.AsEnumerable <DSResource>().GetEnumerator(); } } } } } return(enumerator); }
} // end AddSourceFile() /// <summary> /// Re-runs the list of registered source files, after clearing the internal /// list of registered source files. /// </summary> /// <remarks> /// It is assumed that when a script runs, it calls some command that causes /// AddSourceFile to be called, thereby re-registering itself. If a script /// produces an error, however, it is kept in the list of source files, so that /// a user can fix the error and call this again without re-registering the /// script. /// /// If a script in appendScripts is already in the list, no change is made (the /// script does not get added again to the end of the list, or moved). If a /// script in prependScripts is already in the list, it gets moved from its /// original position to the front. /// </remarks> public void Reload(CommandInvocationIntrinsics invokeCommand, IList <string> appendScripts, IList <string> prependScripts, string dataDisplayName, // for verbose messages IPipelineCallback pipe) { if (null == pipe) { throw new ArgumentNullException("pipe"); } pipe.WriteVerbose("Dumping old {0}...", dataDisplayName); m_DumpContent(); if (null != appendScripts) { foreach (var newScript in appendScripts) { // Unlike the prepend case, here we don't change the position of the // script in the list if it's already in it. if ((null != newScript) && m_sourceFilesSet.Add(newScript)) { pipe.WriteVerbose("Appending script: {0}", newScript); m_sourceFiles.AddLast(newScript); } } } if (null != prependScripts) { foreach (var newScript in prependScripts) { if (null != newScript) { if (m_sourceFilesSet.Remove(newScript)) { pipe.WriteVerbose("Prepending (moving) script: {0}", newScript); m_sourceFiles.Remove(newScript); } else { pipe.WriteVerbose("Prepending script: {0}", newScript); } m_sourceFiles.AddFirst(newScript); } } } // It's possible that there's conditional logic in the scripts that causes // different scripts to run, so we'd better clear out the existing source // files list (after making a copy). var oldSourceFiles = m_sourceFiles.ToArray(); m_sourceFiles.Clear(); m_sourceFilesSet.Clear(); foreach (string sourceScript in oldSourceFiles) { try { // If there are errors parsing the file, then it won't be run, and if // it doesn't get run, something won't call AddSourceFile, and if it // doesn't call AddSourceFile, we won't save the script file to run // again next time someone calls Reload. So we'll save the script name // in the "files to run" /now/, instead of later. pipe.WriteVerbose("Adding {0} from: {1}", dataDisplayName, sourceScript); if (AddSourceFile(sourceScript)) { ScriptBlockAst ast = InvokeScriptCommand.LoadScript(sourceScript); // TODO: should I do anything with any output? InvokeScriptCommand.InvokeScript(invokeCommand, ast.GetScriptBlock(), true); } else { // I don't think it should be possible to get here. Util.Fail("How did we get here?"); } } catch (DbgProviderException dpe) { pipe.WriteError(dpe.ErrorRecord); } catch (RuntimeException re) { pipe.WriteError(re.ErrorRecord); } } } // end Reload()