Parse variable names and variable values in the Powershell code
// script "PS_variable values.cs"
/*/ r %folders.ProgramFiles%\PowerShell\7\System.Management.Automation.dll; /*/ //.
using System.Management.Automation.Language;
script.setup(trayIcon: true, sleepExit: true);
//..
string s = """
$Hash = @{
Path = "D:\\c.txt"
Encoding = 'UTF8'
}
$string = "hello"
$int = 888
""";
Token[] tokens;
ParseError[] errors;
var parsedCode = Parser.ParseInput(s, out tokens, out errors);
foreach (var ast in parsedCode.FindAll(astItem => astItem is AssignmentStatementAst, true))
{
var assignmentAst = (AssignmentStatementAst)ast;
if (assignmentAst.Left is VariableExpressionAst variableExpressionAst)
{
var variableName = variableExpressionAst.VariablePath.UserPath;
var variableValueAst = assignmentAst.Right;
var variableValue = variableValueAst.Extent.Text.Trim();
Console.WriteLine($"variableName: {variableName}");
Console.WriteLine($"variableValue: {variableValue}");
}
}