将powershell变量内联扩展为cmdlet参数? [英] Inline expansion of powershell variable as cmdlet parameter?

查看:35
本文介绍了将powershell变量内联扩展为cmdlet参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调用 cmdlet 时,是否可以以某种方式扩展 powershell 变量的值,使其充当 cmdlet 的参数(具有相关值)?

When calling a cmdlet, is it possible to expand the value of a powershell variable somehow so it acts as a parameter (with associated values) for the cmdlet?

这是我正在尝试的示例:

Here's an example of what I'm trying:

$CREDENTIALED_SECTION = "-Username $USER_NAME -Password $PASSWORD"
.
.
.


Invoke-Sqlcmd -ServerInstance "$SERVER_NAME" -Query "$SQL_STATEMENT" "$CREDENTIALED_SECTION" -Database "$DATABASE"

Invoke-Sqlcmd 运行时出现问题.它告诉我找不到接受-Username my username -Password my password"的位置参数,因此它正在扩展变量但没有正确地将其作为一组发送参数.有没有办法做我在这里尝试的事情?

The problem comes when Invoke-Sqlcmd runs. It tells me that a positional parameter cannot be found that accepts "-Username my username -Password my password" So it's expanding the variable but not properly sending it as a set of parameters. Is there a way to do what I'm trying here?

推荐答案

您可以使用哈希表将这样的参数传递给 PowerShell 命令,例如:

You can pass parameters like this to a PowerShell command using a hashtable instead e.g.:

$CREDENTIALED_SECTION = @{Username=$USER_NAME; Password=$PASSWORD}

Invoke-Sqlcmd -ServerInstance $SERVER_NAME -Query $SQL_STATEMENT @CREDENTIALED_SECTION -Database $DATABASE

请注意,在这种情况下,不必引用 PowerShell 变量.您还需要在命令调用中使用 splatting 语法,例如@<hashtable_with_parameter_name_value_pairs>.

Note that it isn't necessary in this case to quote the PowerShell variables. You also need to use the splatting syntax in the command invocation e.g. @<hashtable_with_parameter_name_value_pairs>.

这篇关于将powershell变量内联扩展为cmdlet参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆