Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline expansion of powershell variable as cmdlet parameter?

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?

like image 278
larryq Avatar asked May 29 '26 02:05

larryq


1 Answers

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

like image 105
Keith Hill Avatar answered Jun 01 '26 12:06

Keith Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!