r/PowerShell • • 21d ago

Question Need help parameterizing SQL queries and with using SqlClient

Trying to use SqlClient to sidestep issues with Invoke-SQLCmd, namely the fact that single quotes in data I'm processing (from a CSV) cause syntax errors. All examples of variable parameterization I found on stack overflow seem to use SqlClient, but I'm running into connection issues:

$creds = Import-PowerShellDataFile -Path $env:Credentials

Write-Output $creds

$db = New-Object System.Data.SqlClient.SqlConnection
$db.ConnectionString = "Server=tcp:$creds.Server;Database=$creds.Database;User=$creds.Username;Password=$creds.Password"
$db.Open()

Getting this error:

Exception calling "Open" with "0" argument(s): "A network-related or instance-specific error occurred     
while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that
the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP
Provider, error: 0 - No such host is known.)"

However, when I use the same credential file for Invoke-SQLCmd, I get no such similar errors:

$query = <pretend there's a valid query here>
Invoke-SQLCmd @creds -Query $query

What am I doing wrong? Is there a better way to avoid the syntax error (and also SQL injection vulnerabilities)?

5 Upvotes

19 comments sorted by

View all comments

4

u/Flettys 21d ago

Check out dbatools on the gallery - https://dbatools.io

It's a one-liner with Write-DbaDbTableData, also note the -AutoCreateTable parameter.

4

u/MrWinks 21d ago

Like buying a car to go to your neighbor’s house. This is an easy solution.

1

u/DoktorLuciferWong 20d ago

might consider trying this the next time i have to do this, though, esp if its a one-liner, and if it can handle csv processing in an even more simplistic/braindead way than i already am

1

u/MrWinks 20d ago

The way you want just requires one more line already, if you remove the username and pass from the connection string when you add it, and then add the credential object to $db.credentials. You don’t need another module for how you were doing it.