简体   繁体   English

Powershell中字符串中变量的替换成员

[英]Substitute member of variable within string in Powershell

I have the following string expression in a PowerShell script: 我在PowerShell脚本中有以下字符串表达式:

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

The schema and table resolve to the values of $schema and $table, respectively. 模式和表分别解析为$ schema和$ table的值。 However, an empty string is supplied for ${col.column_name}. 但是,为$ {col.column_name}提供了一个空字符串。 How can I dot into the member of a variable as part of a string substitution? 如何作为字符串替换的一部分插入变量的成员?

怎么样:

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

I think the problem you're having is mainly syntax related. 我认为你遇到的问题主要是语法相关的。 If you have a variable named $foo, ${foo} references the same variable. 如果你有一个名为$ foo的变量,$ {foo}引用相同的变量。 So, the ${table} and ${schema} references in your sql string work ok. 因此,sql字符串中的$ {table}和$ {schema}引用可以正常工作。

The issue is with ${col.column_name}. 问题在于$ {col.column_name}。 Your variable (I assume) is called $col, and has a member named column_name. 您的变量(我假设)称为$ col,并且具有名为column_name的成员。 As Robert and Steven both indicate in their answers, to refer to this, you should use $($col.column_name). 正如Robert和Steven在他们的答案中指出的那样,要引用它,你应该使用$($ col.column_name)。 In general, $(expression) will be replaced with the value of the expression. 通常,$(表达式)将替换为表达式的值。

The reason for allowing braces in variable names is so that variables can have unusual characters in their names. 允许变量名称括号的原因是变量的名称中可能包含不常见的字符。 I would recommend not using the ${} syntax (unless you have a compelling reason), and replacing it with straight $var references for variables and $($var.member) for member references in strings. 我建议不要使用$ {}语法(除非你有令人信服的理由),并将其替换为变量的直接$ var引用和字符串中成员引用的$($ var.member)。

One way would be: 一种方法是:

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

Another option would be 另一种选择是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM