Forum Discussion

Dre45's avatar
Dre45
Copper Contributor
Oct 11, 2022

SQL Database exists in PowerShell

Good evening everyone. I am on my 2nd homework assignment for PowerShell. Check for the existence of a database named ClientDB. Output a message to the console that indicates if the database exists or if it does not. If it already exists, delete it and output a message to the console that it was deleted.

 

Here is my script I have so far but I need to add the database check in the beginning but I don't know how to write the check using PowerShell.

 

Try {

$DBname = "ClientDB"

$SqlServer = ".\SQLEXPRESS"

$CreateTableQuery = @"

use $DBname

CREATE TABLE Client_A_Contacts

(

first_name varchar(20),

last_name varchar(20),

city varchar(20),

county varchar(20),

zip varchar(20),

officePhone varchar(20),

mobilePhone varchar(20)

)

"@

Import-Module sqlps -DisableNameChecking

$ServerObject = New-Object Microsoft.SqlServer.Management.Smo.Server($SqlServer)

$DBobject = New-Object Microsoft.SqlServer.Management.Smo.Database($ServerObject,

$DBname)

$DBobject.Create()

Write-Host $DBobject "create success @ " $DBobject.CreateDate

Invoke-sqlcmd -ServerInstance $SqlServer -Database $DBname -Query $CreateTableQuery

Pop-Location

Import-Csv "NewClientData.csv" | ForEach-Object {Invoke-sqlcmd -ServerInstance $SqlServer

-Database $DBname -Query "insert into dbo.Client_A_Contacts values

('$($_.first_name)','$($_.last_name)','$($_.city)','$($_.county)','$($_.zip)','$($_.officePhone)','$($

_.mobilePhone)')"}

}

catch [System.OutOfMemoryException] {

Write-Host "Caught: System.OutOfMemoryException"

}

Invoke-Sqlcmd -Database ClientDB –ServerInstance .\SQLEXPRESS -Query ‘SELECT *

FROM dbo.Client_A_Contacts’ > .\SqlResults.txt

 

No RepliesBe the first to reply

Resources