0

In PowerShell, I've a ScriptBlock variable:

$my_scriptblock = { .... }

If I do $my_scriptblock.GetType().Name I get the type as ScriptBlock correctly.

But I'm using Get-Variable to collect all the user variables (I need it for some reason). But when I collect the variables using Get-Variable, they are converted to type PSVariable.

How do I get the variable type of a variable/object that is returned by Get-Variable?

Edit: more info

$my_scriptblock_var = Get-Variable | Where-Object { ('my_scriptblock' -Contains $_.name) }

Now, if you do $my_scriptblock_var.GetType().Name I get the type as PSVariable. Which is correct, Get-Variable will return an object it is designed to return.

My question is how do I get the original Type back?

Also, is there an alternate method I should consider to collect all user variables?

5
  • Does this help? Commented Apr 10, 2018 at 18:26
  • I think that I understand your issue, but could you please provide an MCV? Commented Apr 10, 2018 at 18:27
  • @jrider: I looked at that before posting the question. My question is entirely different as the referenced question is not related to Get-Variable specifically. Commented Apr 10, 2018 at 18:32
  • Get-Variable | % { $_.Value.GetType() } Commented Apr 10, 2018 at 18:40
  • @PetSerAl: perfect, this works. Can you add this as an answer as well. EBGreen's answer below works as well. I'm not decent at powershell enough to judge which one is "Technically Accurate and Correct" way to use it. But it would be great to have this in the answers as well. - Thanks Commented Apr 10, 2018 at 18:46

2 Answers 2

3

Well I have a way to do it, but I would say that the requirement itself is horrible.

$var1 = (get-Date)
$gottenVar = (get-variable -name var1)
$gottenVar.Value.GetType().Name
Sign up to request clarification or add additional context in comments.

2 Comments

Use of Invoke-Expression is unnecessary here (and is generally discouraged). In your third line, just do $gottenVar.Value.GetType().Name
Good call. I still think there is an issue in the basic design of the script though. :)
1

Get-Variable on its own returns the underlying variable objects. To just get the values use Get-Variable -value.

3 Comments

Sorry, but I'm not looking to get the value of the variable. I am looking to get the type of the variable, which in my case should be ScriptBlock
You need to have the variable value in order to get its type. e.g. `Get-Variable -Value | foreach { $_.GetType().Name }
ah, makes sense. Just what PerSerAl says in the comment. Thanks,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.