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

查看:220
本文介绍了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"

当调用-SQLCMD运行的问题就来了。它告诉我,接受一个位置参数无法找到-Username 我的用户名 -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的变量。您还需要使用泼洒语法命令调用例如 @< 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天全站免登陆