powershellvariables

How to get the string representation of a variable's name?


I'm working with PowerShell and I have a variable defined like this:

$name = "John"

I'm trying to find a way to get the string representation of the variable's name, which in this case would be name (without the $ symbol).

Is there a built-in method or a reliable technique to achieve this in PowerShell? I'm looking for a solution that would work for any variable, not just this specific example.


Solution

  • Assuming you have a piece of source code like described, you can use the [System.Management.Automation.Language.Parser]::ParseInput(...) method to parse it, at which point you can search the resulting syntax tree for variable expressions:

    # define source code literal 
    $sourceCode = '$name = "John"'
    
    # parse source code to AST
    $syntaxTree = [System.Management.Automation.Language.Parser]::ParseInput($sourceCode, [ref]$null, [ref]$null)
    
    # search for all variable expressions on the left-hand side of `=`
    $variableAssignmentTargets = $syntaxTree.FindAll({
      param($childAST)
    
      $childAST -is [System.Management.Automation.Language.VariableExpressionAst] -and 
      $childAST.Parent -is [System.Management.Automation.Language.AssignmentStatementAst] -and 
      $childAST -eq $childAST.Parent.Left
    }, $true)
    
    # process the found expressions
    $variableAssignmentTargets |ForEach-Object {
      Write-Host "Found variable with path '$($_.VariablePath)' on line $($_.Extent.StartLineNumber), position $($_.Extent.StartColumnNumber)"
    }
    

    Which in this case would yield the message:

    Found variable with path 'name' on line 1, position 1
    

    The use of AST.FindAll() means you can find all such variable assignments in a complex piece of code:

    $sourceCode = @'
    $a = 123
    $b = $a + ($c = 2)
    '@
    
    # ...
    

    For which we can expect the output:

    Found variable with path 'a' on line 1, position 1
    Found variable with path 'b' on line 2, position 1
    Found variable with path 'c' on line 2, position 12