#requires -version 2.0 # ----------------------------------------------------------------------------- # Script: Get-VariableDefinition.ps1 # Author: Jeffery Hicks # http://jdhitsolutions.com/blog # Date: 3/3/2011 # Keywords: # Comments: # # ----------------------------------------------------------------------------- Function Get-VariableDefinition { <# .Synopsis Get a variable definition. .Description Search PowerShell's history buffer for a variable and return the command that was used to define it. To get the most value from this, make sure your $MaximumHistoryCount is set to a high value. This function cannot get definitions for variables defined in profile scripts. .Parameter Name The name of the variable you want to find without the $. .Example PS C:\> Get-VariableDefinition j $j=(Get-Wmiobject win32_volume -filter "name='J:\\'") .Notes NAME: Get-VariableDefinition VERSION: 1.0 AUTHOR: Jeffery Hicks LASTEDIT: 03/03/2011 Learn more with a copy of Windows PowerShell 2.0: TFM (SAPIEN Press 2010) .Link http://jdhitsolutions.com/blog/2011/03/get-variable-definition/ .Link Get-Variable Get-History .Inputs None .Outputs String #> [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 #define an optional alias Set-Alias -name gvd -Value Get-VariableDefinition