PowerShell Get Variable Name
PowerShell provides the Get-Variable cmdlet to retrieve information about all the variables defined within a session or a specific scope. The cmdlet returns a collection of variable objects containing details like the variable name, value, scope, etc.
Here is an example of using the Get-Variable cmdlet:
$variable = "Hello, World!"
$number = 42
# Retrieve all variables in the current session
$allVariables = Get-Variable
# Loop through the variable collection and display details
foreach ($var in $allVariables) {
"Name: $($var.Name)"
"Value: $($var.Value)"
"Scope: $($var.Scope)"
"Description: $($var.Description)"
"Is Constant: $($var.IsConstant)"
"Is Private: $($var.Private)"
"-----"
}
This example creates two variables, ‘$variable’ and ‘$number’, with different types of values. The Get-Variable cmdlet is then used to retrieve all the variables in the current session and store them in the ‘$allVariables’ variable. The foreach loop iterates over each variable object and displays its name, value, scope, description, and other properties.