# Starting Script section - All scripts get this
#=================================================================================
# Gather the start time of the script
$StartTime = Get-Date
#Set variable to be used in logging events
$whoami = whoami
# Load MOMScript API
$momapi = New-Object -comObject MOM.ScriptAPI
#Log script event that we are starting task
$momapi.LogScriptEvent($ScriptName,$EventID,0,"`n Script is starting. `n Running as ($whoami).")
#=================================================================================
# Begin MAIN script section
#=================================================================================
Write-Host "Script is starting. `nRunning as ($whoami). `nSQLServer: ($SQLServer)."
#Clear any previous errors
IF($Error){$Error.Clear()}
##### Begin Source SQL Query Section
# Connect to SQL and then Query the database
$SQLConnection = New-Object System.Data.SqlClient.SqlConnection
$SQLConnection.ConnectionString = "Server=$SQLServer;Integrated Security=True"
TRY
{
Write-Host "Opening Connection using connect string: ($SQLServer)."
$SQLConnection.Open()
}
CATCH
{
Write-Host "ERROR opening connection to: ($SQLServer). Will Attempt using Name,Port"
IF ($SQLServer -match "\\")
{
#Drop the backslash and named instance
$SQLServer = ($SQLServer.Split("\"))[0]
}
#Use only the first port if passed a comma seperated list
IF ($TcpPorts -match ",")
{
$TcpPorts = ($TcpPorts.Split(","))[0]
}
#Make a new connect string with the port
$SQLServer = $SQLServer + "," + $TcpPorts
#Connect attempt
TRY
{
Write-Host "Opening Connection using connect string: ($SQLServer)."
$SQLConnection.ConnectionString = "Server=$SQLServer;Integrated Security=True"
$SQLConnection.Open()
}
CATCH
{
Write-Host "ERROR opening connection to: ($SQLServer). `nTERMINATING. `nError is: ($Error)."
EXIT
}
}
#Clear any previous errors
IF($Error){$Error.Clear()}
Write-Host "Connected to SQL Server: ($SQLServer). `nRunning SQL command to Create SQL Login and assign permissions for Healthservice."