Command GetCommand(CommandAst commandAst)
{
var firstCommandElement = commandAst.CommandElements.First();
object command = null;
bool useLocalScope = commandAst.InvocationOperator != TokenKind.Dot;
if (firstCommandElement is ScriptBlockExpressionAst)
{
command = (firstCommandElement as ScriptBlockExpressionAst).ScriptBlock;
}
else //otherwise we evaluate it and get the result
{
command = EvaluateAst(firstCommandElement);
if (command is PSObject)
{
command = (command as PSObject).BaseObject;
}
}
//if it's a script block, we are only interested in its Ast (which is indeed always a ScriptBlockAst)
if (command is ScriptBlock)
{
command = (command as ScriptBlock).Ast as ScriptBlockAst;
}
//let's check if we got something useful to execute
if (command is ScriptBlockAst)
{
return new Command(command as ScriptBlockAst, useLocalScope);
}
else //all other objects will converted as a string with ToString(). This is normal powershell behavior!
{
return new Command(command.ToString(), false, useLocalScope);
}
}