Get My Variable Revisited

Last year I wrote a few articles on working with variables. One task I needed was to identify the variables that I had created in a given PowerShell session with a function I wrote called Get-MyVariable. I also posted an article on identifying the object type for a variable value. While trying to find something today I realized I could combine the two ideas.

One approach would be to leave my original function alone. When I need the variable value type, I could simply to this:


PS C:\> get-myvariable | Select Name,Value,@{Name="Type";Expression={$_.Value.GetType().Name}}

Name Value Type
---- ----- ----
a 5/28/2012 8:45:25 AM DateTime
bigp ps | where {$_.ws -gt 1... ScriptBlock
cert [Subject]... X509Certificate2
dirt Param([string]$Path=$en... ScriptBlock
...

See the value in having a function that writes to the pipeline? However, I wanted this to be the default behavior so I decided to incorporate it into my original function. I also realized that there may be situations where I don’t want this information so I added a -NoTypeInformation switch parameter. The changes to my original function were minimal.


#filter out some automatic variables
$filtered=$variables | Where {$psvariables -notcontains $_.name -AND $_.name -notmatch $skip}

if ($NoTypeInformation) {
#write results with not object types
$filtered
}
else {
#add type information for each variable
Write-Verbose "Adding value type"
$filtered | Select-Object Name,Value,@{Name="Type";Expression={$_.Value.GetType().Name}}
}

Now, I can run a command like this:


PS S:\> get-myvariable | where {$_.type -eq "Scriptblock"} | Select name

Name
----
bigp
dc01
dirt
disk
doy
run
up

I suppose I could further refine the function to do filtering in place for a specific type. But I’ll leave that exercise to you.

Download Get-MyVariable2 and try it out for yourself.