Inline expansion of powershell variable as cmdlet parameter?

空扰寡人 提交于 2019-12-02 02:44:56

问题


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"

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?


回答1:


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

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>.



来源:https://stackoverflow.com/questions/12414763/inline-expansion-of-powershell-variable-as-cmdlet-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!