PowerShell hash table conditional assignment

powershell

I have this hash table in a PowerShell script (shortened with a few examples but contains about 8 or so items in it):
–Code previous to this hash table builds the $i variable so I will just supply it for this example of what it should be. It is dependent upon what edition of SQL is on the server. So SQL 2008 R2 default instance would be "MSSQL10_50.MSSQLServer".


$i = 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER'
$SQLPaths = @{
   'DefaultData'=(Get-ItemProperty "$i\MSSQLServer").DefaultLog;
   'RepWorking'=(Get-ItemProperty "$i\Replication").WorkingDirectory
}

My question/issue…Is there a shortcut way of testing this registry path (Test-Path) within the hash table before it sets the value, or tries to? I have some keys just like this that if the feature or setting was never set then the key will not actually exist. Which is fine but how can I ignore it if it does not, and just let the value be null in the hash table?

Best Answer

In PowerShell the if statement can be used as an expression:

$i = 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER'
$SQLPaths = @{
   'DefaultData'= if (Test-Path "$i\MSSQLServer") { 
                     (Get-ItemProperty "$i\MSSQLServer").DefaultLog
                  } else {
                     $null
                  };
   'RepWorking'=(Get-ItemProperty "$i\Replication").WorkingDirectory
}

Also if you're using the PowerShell Community Extensions (PSCX) it adds a Invoke-Ternary (alias ?:) function which could make this less verbose:

$i = 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER'
$SQLPaths = @{
   'DefaultData'= ?: {Test-Path "$i\MSSQLServer"} `
                     { (Get-ItemProperty "$i\MSSQLServer").DefaultLog } `
                     { $null };
   'RepWorking'=(Get-ItemProperty "$i\Replication").WorkingDirectory
}