# verify a sql server connection

**URL:** <https://forums.powershell.org/t/verify-a-sql-server-connection/1443>\
**Category:** PowerShell Help\
**Created:** [December 31, 2011, 6:30pm UTC](https://forums.powershell.org/t/verify-a-sql-server-connection/1443 "2011-12-31T18:30:00Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![archives](https://avatars.discourse-cdn.com/v4/letter/a/bb73d2/32.png) [@archives](https://forums.powershell.org/u/archives)\
**Post date:** [December 31, 2011, 6:30pm UTC](https://forums.powershell.org/t/verify-a-sql-server-connection/1443/1 "2011-12-31T18:30:00Z")

</div>

by antonela at 2013-03-22 03:42:02

> I use sqlcmd -S $Server -d db -b -Q "EXEC pr\_prova" \>\>"$FileLog"  
> in a file.ps1, but before to do this command I would like to verify if the connection was successfully established with sql server.  
>   
> If so, I go ahead and launch my stored procedure using my sqlcmd-…,   
> If not, I want to exit from my file.ps1 (and return an errorr). How can I do to write in a log file ($FileLog) that the connection with db was\wasn’t ok?  
>   
> At the end of a cmd I used **exit /B %errorlevel%** to return the result of my job.This value is get in input from another software which uses it to set an indicator.  
> If I use $? can I have the same result?  
>   
> Thanks

by antonela at 2013-03-22 06:19:49

> I found:  
>   
> **$SqlServer ="SQL\_S"  
> $SqlCatalog = â€œmasterâ€  
> $SqlConnection = New-Object System.Data.SqlClient.SqlConnection  
> $SqlConnection.ConnectionString = â€œServer = $SqlServer; Database = $SqlCatalog; Integrated Security = Trueâ€  
> $SqlConnection.Open()  
> if($SqlConnection.state -eq â€œOpenâ€)  
> {  
> echo â€œ$sqlserver â€“ Connection established db=$SqlCatalog : $(get-date -format yyyy.MM.dd-HH.mm.ss)â€ \>\> $FileLog  
> #c:\servers.out  
> $SqlConnection.Close()  
> echo â€œSuccesâ€  
> }  
> else  
> {  
> echo â€œ$sqlserver â€“ No connection db=$SqlCatalog : $(get-date -format yyyy.MM.dd-HH.mm.ss)â€ \>\> $FileLog  
> }**  
>   
> But how could I read the value of my Sqlserver ($SqlServer) from an .ini file?  
> [Servers]  
> SqlServer=SQL\_S

---

<div class="post-metadata">

**Author:** ![dotnVo](https://avatars.discourse-cdn.com/v4/letter/d/4af34b/32.png) [@dotnVo](https://forums.powershell.org/u/dotnVo)\
**Post date:** [May 16, 2024, 9:03pm UTC](https://forums.powershell.org/t/verify-a-sql-server-connection/1443/2 "2024-05-16T21:03:40Z")

</div>

Closed on May 16, 2024, 9:03pm UTC


