Replace variable element inside string in Powershell

I have the following string expression in a PowerShell script:

"select count(*) cnt from ${schema}.${table} where ${col.column_name} is null" 

The schema and table allow the values โ€‹โ€‹of $ schema and $ table, respectively. However, an empty string is provided for $ {col.column_name}. How can I insert a variable member as part of string substitution?

+6
string powershell
source share
3 answers

What about:

 "select count(*) cnt from $schema.$table where $($col.column_name) is null" 
+9
source share

I think the problem you are facing is mainly related to the syntax. If you have a variable named $ foo, $ {foo} refers to the same variable. Thus, the links $ {table} and $ {schema} in your sql row work fine.

The problem is with $ {col.column_name}. Your variable (I guess) is called $ col and has a member named column_name. As Robert and Stephen point out in their answers, you must use $ ($ col.column_name) to refer to this. In general, $ (expression) will be replaced by the value of the expression.

The reason to allow curly braces in variable names is because variables can have unusual characters in their names. I would recommend that you do not use the $ {} syntax (unless you have a good reason) and replace it with direct links to the $ var and $ ($ var.member) variables for link references in lines.

+4
source share

One of the methods:

 "select count(*) cnt from $schema.$table where $($col.column_name) is null" 

Another variant:

 "select count(*) cnt from {0}.{1} where {2} is null" -f $schema, $table, $col.column_name 
+3
source share

All Articles