Test that a variable exists from a constructed string

Some of you guys will read this and think… this is a guy who doesn’t know what he is doing, and you would be right…unfortunately. I am very much a powershell novice.

I am sure there is a better way to do what I am trying to achieve, but alas, I am posting on a powershell help forum.

I have a hashtable
$HashTable = [ordered]@{}

I am running various commands and inputing the keys/values into a hashtable as a type of “logging” or lookup table.


$41Result = CISRunSQLScript $Hostname "master" $CISChecks41 $SQL_Script_Results
$hashTable.Add("4.1 Ensure 'MUST_CHANGE' Option is set to 'ON' for All SQL Authenticated Logins (Not Scored)", $41Result[0].Result)

The $41Result[0].Result can be PASSED or FAILED. However, I also include a 2nd SQL datatable in the results that can normally be accessed via $41Result[1]. It basically contains information on what made the test fail.

Later in the script, I am searching all the results of the hashtable to look for any result that has FAILED. I am dynamically reconstructing the string, such as $41Result[1] and using invoke-expression to show the datatable contents in the output window. The problem I am having is trying to test and make sure the variable actually exists. Some results do not have multiple datatables. (Get-Variable ‘a’).Value does work to give me the name of the variable, but Get-Variable doesn’t like another Get-Variable to be placed in front of it, as you can see in my commented out if conditional.

So, is there a way that I can take a string that I am executing with invoke-expression and actually ascertain the value within it (which is another variable in the script) actually exists? Any other ways would be welcomed as well.


$HashTable.GetEnumerator() | Where-Object {$_.Value -eq "FAILED"} | ForEach-Object{
Write-Output $_.key
$a = $($_.key).Substring(0, 4)
$a = $a.replace(".", "")
$a = "" + $a.trim() + "Result[1]"
(Get-Variable 'a').Value ##this returns the variable name of the SQL result set above such as $Result

#If ((Get-Variable (Get-Variable $a)).Value -ne $null) {
#$a = "$" + $a + " | ft"
#Invoke-Expression $a
#}
Write-Output ""
}

So you don’t know the variable name so you are using get-variable to find it? If you want the contents of the variable you don’t need get-variable or invoke-expression. You can simply execute the variable itself and it’s default output formatting would write it out. You could also access elements of the hash table via dot notation. You could possibly use .tostring() as well to see the contents. If there isn’t another answer later when I have time, I’ll give a small example.