CodexBloom - AI-Powered Q&A Platform

PowerShell script fails to connect to SQL Server with specific authentication error

👀 Views: 3 💬 Answers: 1 📅 Created: 2025-05-31
PowerShell SQL Server Authentication

I'm running into an issue while trying to connect to a SQL Server instance from my PowerShell script. I'm using SQL Server 2019 with Windows authentication, and I've tried the following command to establish the connection: ```powershell $server = 'localhost'; $database = 'myDatabase'; $connectionString = "Server=$server;Database=$database;Integrated Security=True;"; $connection = New-Object System.Data.SqlClient.SqlConnection($connectionString); $connection.Open(); ``` However, I'm getting the following error message: ``` SqlException: Login failed for user 'DOMAIN\User'. ``` I've verified that the user has the correct permissions on the database, and I can connect to the same SQL Server instance using SQL Server Management Studio without any issues. To troubleshoot further, I tried using SQL authentication instead by modifying the connection string: ```powershell $connectionString = "Server=$server;Database=$database;User Id=myUser;Password=myPassword;"; ``` This also throws an error: ``` SqlException: Login failed for user 'myUser'. ``` I checked the SQL Server settings and confirmed that SQL Server authentication is enabled. I've also tried running the PowerShell script as an administrator and disabling any firewalls, but nothing seems to work. Is there a particular setting or configuration I might be missing that could cause these authentication issues? Any insights on how to successfully connect to my SQL Server from PowerShell would be greatly appreciated!