The title pretty much says it. I’m trying to write a ICustomVisitor to manipulate a PowerShell AST and then generate a script from the AST. I’ve been using an EmptyScriptExtent object as the IScriptExtent value for my AST node constructors for any new nodes that I insert into the tree. The ScriptBlockAst.ToString method appears to reference the Extent under the hood, which in my case is empty.
Looking through the source code, I couldn’t find anything that looked like a AST to string generator.
Does anyone know if the PowerShell SDK provides this functionality by default or if there are any open source libraries that can generate PowerShell code from a PowerShell AST?
Here is what I have so far:
Type type = typeof(IScriptExtent).Assembly.GetTypes()
.Where(x => x.Name.Contains("EmptyScriptExtent"))
.First();
IScriptExtent? extent = (IScriptExtent?)Activator.CreateInstance(type);
ClassicAssert.IsNotNull(extent);
ScriptExtent empty = new ScriptExtent(null, null);
List<CommandElementAst> elements = new List<CommandElementAst>();
elements.Add(new StringConstantExpressionAst(extent, "gci", StringConstantType.BareWord));
elements.Add(new StringConstantExpressionAst(extent, "C:\", StringConstantType.SingleQuoted));
CommandAst command = new CommandAst(extent, elements, TokenKind.Unknown, new List<RedirectionAst>());
StatementBlockAst statements = new StatementBlockAst(extent, new StatementAst[] { command }, new TrapStatementAst[0]);
ParamBlockAst parameters = new ParamBlockAst(extent, new AttributeAst[0], new ParameterAst[0]);
ScriptBlockAst block = new ScriptBlockAst(extent, parameters, statements, false);
//AstToXmlConverter converter = new AstToXmlConverter();
string text = block.ToString();
The issue is that the text variable is always empty, and I can’t figure out how to generate a PowerShell script from this AST.