From 8354d1a3827c7483b010675f6b2e14abe349e21e Mon Sep 17 00:00:00 2001 From: "Dariy.Nurgaleev" Date: Tue, 17 Mar 2020 23:22:20 +0700 Subject: [PATCH] validation with function --- .../Installers/Validate-SQLExpress.ps1 | 46 +++++++++++++------ 1 file changed, 32 insertions(+), 14 deletions(-) diff --git a/images/win/scripts/Installers/Validate-SQLExpress.ps1 b/images/win/scripts/Installers/Validate-SQLExpress.ps1 index 8a0b78fd..db246910 100644 --- a/images/win/scripts/Installers/Validate-SQLExpress.ps1 +++ b/images/win/scripts/Installers/Validate-SQLExpress.ps1 @@ -1,15 +1,33 @@ -$sqlConn = New-Object System.Data.SqlClient.SqlConnection -$sqlConn.ConnectionString = "Server=$env:computername\SQL2019;Integrated Security=false;User ID=sa; Password=P@ssword!!" -$sqlConn.Open() -$str1="" -$sqlConn.State -IF (Compare-Object $sqlConn.State $str1) -{ -Write-Host "Failed attempt" -exit 1 +function Test-SqlConnection { + param( + [Parameter(Mandatory)] + [string]$ServerName, + + [Parameter(Mandatory)] + [string]$IntegratedSecurity, + + [Parameter(Mandatory)] + [string]$UserName, + + [Parameter(Mandatory)] + [string]$Password + ) + + $ErrorActionPreference = 'Stop' + + try { + $connectionString = 'Server={0};Integrated Security={1};User ID={2};Password={3}' -f $ServerName,$IntegratedSecurity,$UserName,$Password + Write-Host -Object "Trying to connect to SQL Express instance: $ServerName" + $sqlConnection = New-Object System.Data.SqlClient.SqlConnection $connectionString + $sqlConnection.Open() + Write-Host -Object "Connection to SQL Express was successful." + } catch { + Write-Host -Object "Connection to SQL Express cannot be established." + exit 1 + } finally { + ## Close the connection when we're done + $sqlConnection.Close() + } } -ELSE -{ -Write-Host "Success" -exit 0 -} \ No newline at end of file +$instanceName = "$env:computername\SQL2019" +Test-SqlConnection -ServerName $instanceName -IntegratedSecurity "false" -UserName "sa" -Password "P@ssword!!" \ No newline at end of file