Last week a question came across my email about how to find out where a variable came from. I thought this was a great question because I've run into this scenario as well. I see a variable but don't recall what command I typed to create it. What I need is an easy way to find the command so I made a tool.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
Every command you enter in a PowerShell session is stored in an internal history buffer. The number of items is controlled by the automatic variable $MaximumHistoryCount which has a default value of 64. When you run the Get-History command, you can see the list of all your recently run commands. Get-History has an alias of h. See a command you want to run again, use Invoke-History, or its alias r and specify the item number. With this information, all I need to do is search my history looking for the command that defined the variable in question.
[cc lang="PowerShell"]
$item=Get-History -Count $MaximumHistoryCount | where {$_.commandline -match "^\`$MyVar="} | Select -Last 1
[/cc]
This would find the command that defined $MyVar. I'm selecting the last history item in case I defined $MyVar earlier. All I care about is the last definition. I'm also using a regular expression so that the command I'm after must start with $MyVar=. Because I'm all about ease of use, I wrapped this core command into a function called Get-VariableDefinition.
[cc lang="PowerShell"]
Function Get-VariableDefinition {
[cmdletBinding()]
Param(
[Parameter(Position=0,Mandatory=$True,HelpMessage="Enter a variable name, without the `$")]
[ValidateNotNullOrEmpty()]
[string]$Name
)
Try
{
#make sure a valid variable name was passed
$verify=Get-Variable $name -ErrorAction Stop
}
Catch
{
Write-Warning "The variable $Name was not found."
}
if ($verify)
{
#search history and get the last assignment
$item=Get-History -Count $MaximumHistoryCount | where {$_.commandline -match "^\`$$Name="} | Select -Last 1
if ($item)
{
#write the Commandline property to the pipeline if something was found
$item.CommandLine
}
else
{
#the variable definition has expired
Write-Host "Failed to find a definition for `$$Name in your existing history." -ForegroundColor Yellow
}
} #close if $verify
} #end Function
[/cc]
The script file also contains an alias definition. If the variable command can't be found then you get a message.
[cc lang="PowerShell"]
PS S:\> gvd myvar
$myvar=gwmi win32_bios
PS S:\> gvd running
$running=gsv | where {$_.status -eq "running"}
PS S:\> gvd j
Failed to find a definition for $j in your existing history.
PS S:\>
[/cc]
In order to get the most out of this, you should increase your $MaximumHistoryCount variable in your PowerShell profile.
[cc lang="PowerShell"]
$MaximumHistoryCount=2048
[/cc]
Download Get-VariableDefinition.ps1