none
How to check if $($var) exists? RRS feed

  • Question

  • Hi guys

    I hope you can help me!

    Let's say I have this:

    $XXX = "TTT"
    
    $Department = "XXX - Hello"
    
    $Test = ($Department.Split(" "))[0]
    
    If($($Test) -eq "TTT") {Write-Host "Does it work?"}
    The If statement is the problem. I would like for it to replace $($Test) with $XXX and then check if that variable exists. But while $Test returns the string "XXX" it doesn't seem to accept that I want to insert a $ sign in front and check if this variable exists. Is there some way of doing this, that I'm just not seeing? I've tried writing it a bunch of different ways without any luck.


    • Edited by Casper83DK Monday, January 20, 2014 9:38 AM
    Monday, January 20, 2014 9:36 AM

Answers

  • Hi Casper,

    the only way to do it that I can think of right now, is this:

    if ((Get-Variable $Test).Value -eq "TTT"){Write-Host "It DOES work!"}

    Cheers,
    Fred


    There's no place like 127.0.0.1

    • Marked as answer by Casper83DK Monday, January 20, 2014 10:13 AM
    Monday, January 20, 2014 9:44 AM

All replies

  • Hi Casper,

    the only way to do it that I can think of right now, is this:

    if ((Get-Variable $Test).Value -eq "TTT"){Write-Host "It DOES work!"}

    Cheers,
    Fred


    There's no place like 127.0.0.1

    • Marked as answer by Casper83DK Monday, January 20, 2014 10:13 AM
    Monday, January 20, 2014 9:44 AM
  • That did it, thank you very much :-)
    Monday, January 20, 2014 10:13 AM
  • that will not always work.  I think this is what you are thinking of:

    if( Get-Variable MyVar -ea 0){
         'Var exists'
    }else{
         'var does not exist'
    }


    ¯\_(ツ)_/¯

    Monday, January 20, 2014 10:25 AM